2014-12-04 44 views
1

以下是代碼。它被用來根據用戶輸入來改變列表中存儲的特定值(25到81之間的值)。我使用第二個列表來決定發生什麼,只有4個值,這也是用戶的輸入。基本上,如果用戶選擇一個特定的值,它將依次變爲下一個值。簡化短列表比較

if list1[value] == list2[3]: 
    list[value] = list2[0] 
elif list1[value] == list2[0]: 
    list[value] = list2[1] 
elif list1[value] == list2[1]: 
    list[value] = list2[2] 
elif list1[value] == list2[2]: 
    list[value] = list2[3] 

我的問題是,我不能找到一種方法,使其更簡單。它看起來很長很醜。它還需要根據額外的輸入執行多次,因此,如果用戶選擇了兩次相同的變量,則每次都會按順序進行更改。

這似乎是這樣一個愚蠢的問題。我一直在想如何簡化這個年齡段,簡單的循環或什麼,但由於某種原因每次都失敗。 我已經試過這樣的事情:

e = value % 4 
if list1[value] == list2[e]: 
    list1[value] = list2[e + 1] 
#This isn't exactly what I had, but something along these lines, maybe in a for loop too etc. 

清單2中包含4串,[colour1,顏色2,colour3,colour4] 列表1中包含這些相同的字符串,但循環一遍又一遍,直到它擊中列表限制由用戶指定。

感謝您的幫助!

+1

列表是什麼樣的? – 101 2014-12-04 23:16:57

+0

列表2有4個字符串,[userColor1,userColor2,userColor3,userColor4] 列表1將具有25到81個值,與列表2相同的字符串,但一遍又一遍地循環,直到達到最大值。 – Jett 2014-12-04 23:20:41

+0

@Jett:你可以編輯這個問題來添加該評論嗎?一眼看到未來的參觀者會更快。 (標籤列表下的'編輯'鏈接) – BorrajaX 2014-12-04 23:21:56

回答

2

相反的「循環」設置數據的列表中,使用的{value: nextvalue}字典,即:

cycler = {0: 1, 1: 2, 2: 3, 3: 0} # replace 0,1,2,3 with the actual values 
if list1[value] in cycler: 
    list1[value] = cycler[list1[value]] 

編輯:

cycler = {list2[i-1]: list2[i] for i in xrange(len(list2))} 
# Note that this works because `list2[-1]` indexes the last element. 
+0

非常感謝,這是有效的。有一件事情是,直到用戶輸入它,我才知道實際值是什麼,所以它有點長。我只需要輸入{list2 [0]:list2 [1],list2 [1],list2 [2]}等等嗎?如果沒有辦法進一步簡化,那麼這是完美的! – Jett 2014-12-04 23:33:42

+0

@Jett添加了代碼來更方便地構建列表。 – tzaman 2014-12-05 08:39:47

0
:從元素列表構建循環儀
for i in range(0, len(list2): 
    if list1[value] == list2[i] : 
     list1[value] = list2[(i+1)%len(list2)]