【发布时间】:2020-12-10 17:57:06
【问题描述】:
我正在尝试创建一个 for 循环,以将第一个列表 num 的内容附加到 num2 + 单词千。我在寻找
nums2 = ['one thousand', 'two thousand', 'three thousand', 'four thousand']。当我尝试运行它时,我得到的只是list indices must be integers or slices, not str。有什么建议吗?
nums = ['one', 'two', 'three', 'four']
nums2 = []
for i in nums:
nums2.append(nums[i] + ' thousand')
编辑(美国东部标准时间下午 1:13,2020 年 12 月 10 日):
这个问题已经被问过了!我的错。
Appending the same string to a list of strings in Python
【问题讨论】:
-
i是实际值,而不是索引。无需在附加语句中再次调用nums。 -
for i in nums:可以是for i in range(len(nums)):。或者只是将nums[i]更改为i。 -
@RandomDavis 它不需要是索引。只需使用该值。
-
您的意思是:
nums2 = [num + ' thousand' for num in nums]?