python - 如何从列表中检索项目 'n'?

标签 python python-3.x list

我是 Python 新手,我正在尝试通过从列表 A、B 和 C 中检索第一项,并将这些值附加到列表 D 中,然后迭代来创建“主列表”。

我正在使用代码:

i = 1
while i < 4:
    listA.append(str(i))
    listB.append(str(i + 10))
    listC.append(str(i + 100))
    i += 1
print(listA, listB, listC)

返回:[1, 2, 3] [11, 12, 13] [101, 102, 103]

我想要的最终结果如下:[1, 11, 101, 2, 12, 102, 3, 13, 103]

我尝试使用以下代码:

while k < 4:
    listD.append([item[k] for item in listA])
    listD.append([item[k] for item in listB])
    listD.append([item[k] for item in listC])
    k += 1

print(listD)

但这会返回错误:TypeError: 'int' object is not subscriptable.

最佳答案

这是一些Python代码:

>>> 
>>> 
>>> A=[1,2,3]
>>> B=[11,12,13]
>>> C=[101,102,103]
>>> 
>>> 
>>> D=[]
>>> 
>>> [D.extend(a) for a in zip(A,B,C)]
[None, None, None]
>>> 
>>> D
[1, 11, 101, 2, 12, 102, 3, 13, 103]
>>> 

所以你的Python代码应该是这样的:

D = []
for i in range(1,4):
    listA.append(str(i))
    listB.append(str(i + 10))
    listC.append(str(i + 100))
[D.extend(a) for a in zip(A,B,C)]
print(D)

这只是一个起点,你可以写得更好。

关于python - 如何从列表中检索项目 'n'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55173165/

相关文章:

java - 如何对 Amazon Alexa 进行 REST API 调用

python - chr() 等效返回一个字节对象,在 py3k

python - 在列表上应用 boolean 值字符串

python - 在 dockerbuild 文件中添加到 pythonpath 的路径

python - 按相邻属性值对 lxml 元素进行分组列表

python - 确定 ‘data’ 的平均值,其中 CONTINUOUS cond=True 的最高数量

python - 如何在 JSON 中编码字节? json.dumps() 抛出 TypeError

python - 将字符串转换为路径对象

python - Python list 本质上是一个链表实现吗?

Python 正在覆盖我的列表