[英]How to replace two elements in a list if both are the same (Python)
I want to replace elements in a list if they coincide in the same list untill there is only an 1 in the list.我想替换列表中的元素,如果它们在同一个列表中重合,直到列表中只有 1。 If I have [1,0,1,0,1], the list becomes [0,0,1,0,0] or something like that, only with an 1... but it doesnt replace elements and it prints the same list...如果我有 [1,0,1,0,1],列表变成 [0,0,1,0,0] 或类似的东西,只有一个 1...但它不替换元素,它打印一样的清单...
import random
p = float(input("Introduzca probabilidad de transmisión: "))
q = 1 - p
usuarios = ['Usuario1','Usuario2', 'Usuario3', 'Usuario 4', 'Usuario5']
transmisiones = []
for i in usuarios:
if random.random() < p:
transmisiones.append(1)
else:
transmisiones.append(0)
print(transmisiones)
for elemento in transmisiones:
if elemento == 1 and transmisiones[0:5] == 1:
transmisiones[elemento] = 0
print(transmisiones)
output:
Introduzca probabilidad de transmisión: 0.6
[1, 1, 0, 0, 0]
[1, 1, 0, 0, 0]
you should write like this你应该这样写
idx= -1
for i in range(len(transmisiones)):
if transmisiones[i] == 1:
idx = i
transmisiones[i] = 0
transmisiones[idx] = 1
the idx
always keep the last index where the value is equal to 1 idx
始终保持最后一个索引值等于 1
if you want all the indices to be saved append them in the a list如果您希望保存所有索引,请将它们附加到列表中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.