[英]Comparing Value of List Index and Integer in Second List
我正在嘗試完成我的第一個Python程序(大約一個月前我才開始上Python課)。 現在,只允許使用標准庫,但是我也可以導入隨機庫。
我想做的是比較兩個列表。 一個是隨機數列表(我已經弄清楚了),第二個是1和0列表。 1表示第一個列表中的數字需要替換為新的隨機數。 0表示他們想保留該號碼。
有人可以幫我一下,並通過它解釋他們的邏輯嗎? 我現在很茫然,非常感謝您能為我提供的任何幫助。
這是我到目前為止的內容:
def replaceValues(distList, indexList):
for i in range (1,len(indexList)):
if indexList[i] = int(1):
然后我有點迷路了。
謝謝!
使用enumerate
。 它使您可以在帶有索引的列表上進行迭代:
import random
control_list = [1, 0, 1] # Your 0's and 1's
numbers_list = [1, 2, 3] # Your random numbers
for index, control in enumerate(control_list):
if control == 0:
numbers_list[index] = random.random()
print numbers_list
# [1, 0.5932577738017294, 3]
請注意,這將替換numbers_list
的元素。 如果不希望這樣,您可以創建一個新列表並使用zip
,它使您可以並行地遍歷兩個列表:
import random
control_list = [1, 0, 1]
numbers_list = [1, 2, 3]
new_list = []
for control, number in zip(control_list, numbers_list):
if control == 0:
number = random.random()
new_list.append(number)
print new_list
# [1, 0.46963935996528683, 3]
在一行中,使用列表推導:
l = [n if c == 1 else random.random() for n, c in zip(numbers_list, control_list)]
print l
# [1, 0.9579195229977218, 3]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.