我有两个列表。我想从其中一个列表中给出的元素中获得三分之一
I have two lists. I would like to make a third from the elements given in one of the lists
抱歉标题混乱!
我有两个列表,比如:
a = [30,55,76,43,27,28]
b = [0,2,3,5]
我想做一个 list c
是 a 的两个元素,即
c = [30,76,43,28] # -> the 0th, 2nd, 3rd, 5th elements of a
我应该使用 zip() function
吗?或者你可以使用简单的 for loop
?
谢谢。
您可以通过 enumerate
函数实现。
>>> a = [30,55,76,43,27,28]
>>> b = [0,2,3,5]
>>> l = []
>>> for i,j in enumerate(a):
for m in b:
if i == m:
l.append(j)
>>> l
[30, 76, 43, 28]
通过list_comprehension.
>>> a = [30,55,76,43,27,28]
>>> b = [0,2,3,5]
>>> [j for i,j in enumerate(a) for m in b if i == m ]
[30, 76, 43, 28]
抱歉标题混乱!
我有两个列表,比如:
a = [30,55,76,43,27,28]
b = [0,2,3,5]
我想做一个 list c
是 a 的两个元素,即
c = [30,76,43,28] # -> the 0th, 2nd, 3rd, 5th elements of a
我应该使用 zip() function
吗?或者你可以使用简单的 for loop
?
谢谢。
您可以通过 enumerate
函数实现。
>>> a = [30,55,76,43,27,28]
>>> b = [0,2,3,5]
>>> l = []
>>> for i,j in enumerate(a):
for m in b:
if i == m:
l.append(j)
>>> l
[30, 76, 43, 28]
通过list_comprehension.
>>> a = [30,55,76,43,27,28]
>>> b = [0,2,3,5]
>>> [j for i,j in enumerate(a) for m in b if i == m ]
[30, 76, 43, 28]