python - 在 Python 中,为什么压缩元素在添加到列表时会分开?

标签 python string algorithm list iterator

我想创建像 A1、B2、C3 和 D4 这样的名字

batches = zip('ABCD', range(1, 5))

for i in batches:
  batch = i[0] + str(i[1])
  print(batch)

这会产生预期的输出:

A1
B2
C3
D4

但是,如果我将列表 batch_list 初始化为空并将每个批处理添加到其中,如下所示:

batch_list = []

batches = zip('ABCD', range(1, 5))

for i in batches:
  batch_list += i[0] + str(i[1])

print(batch_list)

输出如下:

['A', '1', 'B', '2', 'C', '3', 'D', '4']

为什么不呢?

['A1', 'B2', 'C3', 'D4']

最佳答案

因为它将您的字符串视为一个数组。

>>> arr = []
>>> arr += 'str'
>>> arr
['s', 't', 'r']

试试这个:

batch_list += [i[0] + str(i[1])]

或者这个:

batch_list.append(i[0] + str(i[1]))

关于python - 在 Python 中,为什么压缩元素在添加到列表时会分开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45781315/

相关文章:

c++ - 在字符串中的偶数位置提取字母?

java - 使用 String split Java 重建字符串

algorithm - 从对集合中创建最小基数集合

algorithm - 这个算法会在 O(n) 内运行吗?

python - sympy 的高级索引?

python - 属性错误 : module 'win32ctypes.pywin32.win32api' has no attribute 'error'

python : Downloading file from the link which is implemented with php

python - dunder方法是继承的吗?

java获取字符串中的下几个单词

algorithm - 找出使总和最小的排列