我有三个清单,说:
a = [1, 2, 3, 4, 5]
b = [a, b, c, d, e]
x = [1, 3, 5]
我想这样做,输出如下:
for item in x:
if item in a:
print(zip(a[x], b))
1a
3c
5e
我对如何打印a
中的相应项目和b
中的项目感到困惑。任何帮助将不胜感激,谢谢。
答案 0 :(得分:2)
a = [1, 2, 3, 4, 5]
b = ['a', 'b', 'c', 'd', 'e']
x = [1, 3, 5]
for i, j in zip(a, b):
if i in x:
print(f"{i}{j}")
或仅使用列表理解:
[print (f"{i}{j}") for i, j in zip(a, b) if i in x]
输出:
1a
3c
5e
但是,如果您的列表较长,则最好对数据进行预处理,建立一个从a
到b
的dict映射值:
d = {k:v for k, v in zip(a, b)}
for k in x:
print('{}{}'.format(k, d[k]))
# 1a
# 3c
# 5e
答案 1 :(得分:1)
这里不需要使用zip
,可以使用index
:
a = [1, 2, 3, 4, 5]
b = ['a', 'b', 'c', 'd', 'e']
x = [1, 3, 5]
for v in x:
i = a.index(v)
if v > -1:
print('{}{}'.format(a[i], b[i]))
# 1a
# 3c
# 5e
答案 2 :(得分:0)
以下是有关“ zip”功能的Python文档:https://docs.python.org/3.3/library/functions.html#zip
您可能还对https://docs.python.org/3/library/itertools.html#itertools.zip_longest感兴趣
和https://pyformat.info/
我将逐步进行操作,以便您了解:
a = [1, 2, 3, 4, 5]
b = ['a', 'b', 'c', 'd', 'e']
x = {1, 3, 5} # I change the type of x to set 'in' statement works much quicker with set than with list
# you can simply iterate over zip item with acces to value from a and b container:
for a_value, b_value in zip(a, b):
if a_value in x:
print("{}{}".format(a_value, b_value)) # you need to format data according to your needs