我对这个问题很好奇:消除列表元素的连续重复,以及如何在Python中实现它.
我想出的是:
list = [1,1,1,1,1,1,2,3,4,4,5,1,2]
i = 0
while i < len(list)-1:
if list[i] == list[i+1]:
del list[i]
else:
i = i+1
Run Code Online (Sandbox Code Playgroud)
输出:
[1, 2, 3, 4, 5, 1, 2]
Run Code Online (Sandbox Code Playgroud)
我觉得还可以.
所以我很好奇,想看看我是否可以删除连续重复的元素并获得此输出:
[2, 3, 5, 1, 2]
Run Code Online (Sandbox Code Playgroud)
为此我做了这个:
list = [1,1,1,1,1,1,2,3,4,4,5,1,2]
i = 0
dupe = False
while i < len(list)-1:
if list[i] == list[i+1]:
del list[i]
dupe = True
elif dupe:
del list[i]
dupe = False
else:
i += 1
Run Code Online (Sandbox Code Playgroud)
但它似乎有点笨拙而不是pythonic,你有更智能/更优雅/更有效的方式来实现它吗?
所以我几天前才开始用 Python 编程。现在,我正在尝试制作一个生成随机列表的程序,然后选择重复的元素。问题是,我的列表中没有重复的数字。
这是我的代码:
import random
def generar_listas (numeros, rango):
lista = [random.sample(range(numeros), rango)]
print("\n", lista, sep="")
return
def texto_1 ():
texto = "Debes de establecer unos parámetros para generar dos listas aleatorias"
print(texto)
return
texto_1()
generar_listas(int(input("\nNumero maximo: ")), int(input("Longitud: ")))
Run Code Online (Sandbox Code Playgroud)
例如,我为 random.sample 选择了 20 和 20,它为我生成了一个从 0 到 20 但位置随机的列表。我想要一个包含随机数并重复的列表。