猿问

反转运算符从随机点反转列表

有没有办法从一些随机索引中反转列表数据。我不想颠倒整个列表,只是其中的一部分。就像,我们有输入列表 a=[4,3,6,2,1,5,7,8]和输出列表 a' = [4,3,5,1,2,6,7,8] 反转点可以在任何地方,并且首选随机选择。



HUWWW
浏览 102回答 1
1回答

紫衣仙女

是否有可能,您可以生成 2 个随机数并使用它们来选择不同的索引aimport randoma = [4,3,6,2,1,5,7,8]b = random.randint(0,len(a))c = random.randint(0,len(a))while c == b :&nbsp; &nbsp; c = random.randint(0,len(a))tmp = a[b]a[b] = a[c]a[c] = tmpprint(a)编辑: 白色索引之间的反转import randoma = [4,3,6,2,1,5,7,8]len_a = len(a)-1b = random.randint(0,len_a)c = random.randint(0,len_a)while c == b :&nbsp; &nbsp; c = random.randint(0,len_a)if(b < c):&nbsp; &nbsp; min = b&nbsp; &nbsp; max = celse:&nbsp; &nbsp; min = c&nbsp; &nbsp; max = bprint(f"{min} {max}")new_list = a[0:min]if(min == 0):&nbsp; &nbsp; for number in a[max::-1]:&nbsp; &nbsp; &nbsp; &nbsp; new_list.append(number)else:&nbsp; &nbsp; for number in a[max:min-1:-1]:&nbsp; &nbsp; &nbsp; &nbsp; new_list.append(number)if(max != len(a)):&nbsp; &nbsp; for number in a[max+1:len_a+1]:&nbsp; &nbsp; &nbsp; &nbsp; new_list.append(number)print(f"a = \t\t{a}")print(f"new_list = \t{new_list}")输出 :4 6a =&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[4, 3, 6, 2, 1, 5, 7, 8]new_list =&nbsp; &nbsp; &nbsp; [4, 3, 6, 2, 7, 5, 1, 8]
随时随地看视频慕课网APP

相关分类

Python
我要回答