【问题标题】:How do you add a string to every string inside of a list? [duplicate]如何将字符串添加到列表中的每个字符串? [复制]
【发布时间】: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]

标签: python for-loop


【解决方案1】:

当您遍历nums 列表时,i 是列表中的每个值;在第一次迭代中,i 等于 one,在第二次迭代中,i 等于 two

因此,当您尝试访问 nums[i] 时,您正在尝试访问 nums["one"](在第一次迭代中),这显然不存在。

要解决这个问题,您可以使用 range 将 for 循环更改为基于索引的循环:

for i in range(len(nums)):
  nums2.append(nums[i] + ' thousand')

或者您可以完全停止尝试从循环内访问列表,并使用 i 的值作为前缀将 thousand 附加到:

for i in nums:
  nums2.append(i + ' thousand')

【讨论】:

  • 很好的解释,谢谢!我非常感谢您的帮助。
【解决方案2】:

在这种情况下,“i”是一个字符串,因为字符串是列表中的元素。尝试在追加中仅使用 i 而不是 nums[i] 。示例:

nums = ['one', 'two', 'three', 'four']
nums2 = []

for i in nums:
     nums2.append(i + ' thousand')

【讨论】:

    【解决方案3】:

    for 循环中的变量 i 引用 nums 列表的各个元素,在这种情况下是字符串。您需要整数作为索引,因此在您的情况下,可以将 for 循环修改为:

    for i,k in enumerate(nums):
     nums2.append(nums[i] + ' thousand')
    

    您可以通过打印 nums2 来检查是否正确:

    print(nums2)
    

    【讨论】:

      【解决方案4】:

      你可以试试:

      nums = ["Ford", "Volvo", "BMW"]
      nums2 = []
      
      for i in nums:
        nums2.append(i + ' thousand')
      

      【讨论】:

        猜你喜欢
        • 2020-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-02
        • 1970-01-01
        • 2013-11-06
        • 2021-08-02
        • 2011-06-16
        相关资源
        最近更新 更多