Choose 1 element per index randomly from list A or B in Python
I have 2 lists in Python and I want to choose, for every index either an element from list A or l开发者_JAVA百科ist B.
I managed to do it easily but this solution has bad performance and it doesn't seem very elegant.
Can anybody sugest an alternative that doesn't rely in these for cycles with if's inside?I'll post the code here:
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
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']
You can do this in a single list comprehension like so:
newList = [x if randint(0,1) else y for x, y in zip(l1, l2)]
I'm not certain whether that actually improves performance much, but it's clean.
How about:
def scramble(list1, list2):
return [random.choice([list1[i], list2[i]]) for i in range(len(list1))]
It assumes len(list1)==len(list2). I'm not sure that this would necessarily be any faster though.
You could use a "clever" list comprehension:
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)]
Though it's less readable.
精彩评论