我在Python中有2个列表,我想为每个索引选择列表A或列表B中的元素。
我设法轻松地做到了,但这个解决方案性能不好,看起来不太优雅 任何人都可以选择不依赖 周期的 if 的替代品吗?
我会在这里发布代码:
def scramble(list1, list2):
finalList = []
for i in range(32): # the list has 32 elements
if randint(1,2) == 1:
finalList.append(list1[i])
else:
finalList.append(list2[i])
return finalList
答案 0 :(得分:10)
import random
from itertools import izip
l1 = ['a', 'b', 'c', 'd', 'e', 'f']
l2 = [0, 1, 2, 3, 4, 5]
[random.choice(pair) for pair in izip(l1, l2)]
# e.g. [0, 1, 'c', 3, 'e', 'f']
答案 1 :(得分:1)
您可以在单个列表理解中执行此操作:
newList = [x if randint(0,1) else y for x, y in zip(l1, l2)]
我不确定这是否真的能提高性能,但它很干净。
答案 2 :(得分:0)
怎么样:
def scramble(list1, list2):
return [random.choice([list1[i], list2[i]]) for i in range(len(list1))]
假设len(list1)== len(list2)。我不确定这会不会更快。
答案 3 :(得分:0)
你可以使用“聪明”的列表理解:
from random import choice
def scramble(l1,l2):
length = min(len(l1),len(l2))
lists = (l1,l2)
return [choice(lists[i]) for i in xrange(0,length)]
虽然它的可读性较差。