在Python中切换两个元素

时间:2015-09-27 14:17:19

标签: python swap shuffle

假设我在一个长列表中有一堆元素,我想根据random.randit(lo,hi)函数得到的输出来切换它们。 例如,我的列表是

L=[(1,hi), (1, bye), (1,nope), (1,yup), (2,hi), (2, bye), (2,nope), (2,yup), (3,hi), (3, bye), (3,nope), (3,yup), (4,hi), (4, bye), (4,nope), (4,yup), (5,hi), (5, bye), (6,nope), (7,yup)]

如果我导入from random import randint然后执行randint(0,(len(L)-1))我得到的数字作为输出我想要将该数字编入索引,并将其与列表中的最后一个元素交换,然后{ {1}}并获取我从该输出获得的数字,将该数字索引的元素与第二个到最后一个元素交换,依此类推,直到我到达开头。这就像我想要完全随机地重新排列列表而不是使用shuffle函数。

**我明白我可以做randint(0,(len(L)-1))如果我得到5作为输出做A = L [19](因为我知道我的列表中的最后一个元素是索引为19)。 然后做L [19] = L [5],使第5个元素取第19个元素放置然后做L [5] = A,这样最后一个元素就变成了第5个元素。但我不知道如何把它写成一个循环。

2 个答案:

答案 0 :(得分:1)

Open3.capture2("C:\temp\test.exe", "arg1", "arg2")

<强>输出

L =[(1,'hi'), (1, 'bye'), (1,'nope'), (1,'yup'), (2,'hi'), (2, 'bye'), (2,'nope'), (2,'yup'), (3,'hi'), (3, 'bye'),
   (3,'nope'), (3,'yup'), (4,'hi'), (4, 'bye'), (4,'nope'), (4,'yup'), (5,'hi'), (5, 'bye'), (6,'nope'), (7,'yup')]


   for i in range(-1, -len(L) -1 ,-1):
    n = randint(0,(len(L) -1))
    L[n], L[i]   =  L[i], L[n]


print(L)

答案 1 :(得分:0)

您可以使用列表推导结构中包含的popappend来随机播放列表。然后,您将从收缩列表中随机弹出一个元素并追加到最后。

from random import randint

L = [(1, 'hi'), (1, 'bye'), (1, 'nope'), (1, 'yup'), 
     (2, 'hi'), (2, 'bye'), (2, 'nope'), (2, 'yup'), 
     (3, 'hi'), (3, 'bye'), (3, 'nope'), (3, 'yup'), 
     (4, 'hi'), (4, 'bye'), (4, 'nope'), (4, 'yup'), 
     (5, 'hi'), (5, 'bye'), (6, 'nope'), (7, 'yup')]

_ = [L.append(L.pop(randint(0, n))) for n in range(1, len(l) - 1)]