lst = ['mylist1','mylist2','mylist3']
for x in lst:
for r in xrange(2):
print x
输出:(将列表中的元素重复两次)
[root@localhost ~]# python test.py
mylist1
mylist1
mylist2
mylist2
mylist3
mylist3
如何随机选择元素:
mylist3
mylist1
mylist3
mylist2
mylist2
mylist1
答案 0 :(得分:2)
您可以先使用列表extend()
将列表中的每个元素加倍,然后对列表进行随机播放
from random import shuffle
lst = ['mylist1','mylist2','mylist3']
lst = lst.extend(lst) # repeat items twice
shuffle(lst)
for x in lst:
print(x)
答案 1 :(得分:1)
或*
(乘法运算符):
lst = lst*2 # repeat items twice
shuffle(lst)
for x in lst:
print(x)
或list comprehension
:
lst = [x for i in range(2) for x in lst] # repeat items twice
shuffle(lst)
for x in lst:
print(x)