[英]Swapping two elements in a list of lists of lists in Python
我在 Python 中有一个列表列表,其中所有子列表都是成对的。
例如,如果有一对['b', 'c']
,那么也会有一对['c', 'b']
。
mylist = [[['a', 'c'], ['e', 'f'], ['b', 'd']],
[['a', 'd'], ['f', 'b'], ['c', 'e']],
[['a', 'e'], ['b', 'c'], ['d', 'f']],
[['a', 'b'], ['d', 'e'], ['f', 'c']],
[['a', 'f'], ['c', 'd'], ['e', 'b']],
[['c', 'a'], ['f', 'e'], ['d', 'b']],
[['d', 'a'], ['f', 'b'], ['e', 'c']],
[['b', 'a'], ['e', 'd'], ['c', 'f']],
[['f', 'a'], ['e', 'c'], ['b', 'e']],
[['e', 'a'], ['c', 'b'], ['f', 'd']]]
我想随机选择一对并与相反的一对交换。 因此,在['a', 'b']
所在的位置,我想将其替换为['b', 'a']
,反之亦然。
然后, mylist
将是:
mylist = [[['a', 'c'], ['e', 'f'], ['b', 'd']],
[['a', 'd'], ['f', 'b'], ['c', 'e']],
[['a', 'e'], ['b', 'c'], ['d', 'f']],
[['b', 'a'], ['d', 'e'], ['f', 'c']],
[['a', 'f'], ['c', 'd'], ['e', 'b']],
[['c', 'a'], ['f', 'e'], ['d', 'b']],
[['d', 'a'], ['f', 'b'], ['e', 'c']],
[['a', 'v'], ['e', 'd'], ['c', 'f']],
[['f', 'a'], ['e', 'c'], ['b', 'e']],
[['e', 'a'], ['c', 'b'], ['f', 'd']]]
我随机选择一对:
randomnumber1 = random.randint(0,len(mylist))
randomnumber2 = random.randint(0,int(mylist/2))
for index, round in enumerate(mylist):
for idx, couple in enumerate(round):
if index==randomnumber1 and idx==randomnumber2:
picked = couple
reversedpair = list(reversed(picked))
到目前为止,很好,我找到了我想要交换的货币对,但是我该如何进行交换呢?
我想合并这个解决方案,但不同的是这是一个列表列表。
您应该随机 select 行和列,然后遍历行和列以找到要交换的相应元素的索引。 找到这些索引后,您可以正常执行交换操作:
selected_row = random.randint(0, len(mylist) - 1)
selected_col = random.randint(0, len(mylist[0]) - 1)
for row in range(len(mylist)):
for col in range(len(mylist[0])):
if mylist[selected_row][selected_col] == mylist[row][col][::-1]:
mylist[selected_row][selected_col], mylist[row][col] = \
mylist[row][col], mylist[selected_row][selected_col]
break
这是一种方法,将随机选择的值保存在变量中并尝试查找匹配项,然后反转每个匹配项:
selected = mylist[randomnumber1][randomnumber2]
for i, sublist in enumerate(mylist):
for j, item in enumerate(sublist):
if item in (selected ,selected[::-1]):
mylist[i][j] = mylist[i][j][::-1]
print(mylist)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.