2015-11-01 144 views
2

說我有下面列出了指數收益率2只列出了一個新的列表(Python 3中):創建基於從第三列表

numbers = [1,2,3,4,5,6] 
letters = [a,b,a,b,c,c] 
state = [False, False, False, False, False, False] 

我所希望做的是從用戶接收兩個輸入用於列表字母長度範圍內的2個索引位置。如果他的選擇對應於諸如a和(索引0和2)的匹配字母,則對於所述位置,列表狀態必須從False更改爲True。此後,它應該創建根據新的國家名單上,從數量越來越索引項,如果狀態元素爲False,然後從列表信件得到索引項新的列表,如果狀態爲真:

choice = 0 
choice_2 = 2 
if letters[choice] == letters[choice_2]: 
    change state[choice] and state[choice_2] to True 
create fourth list from list state and use values from numbers and letters 
For i in range(len(state)): 
    if state[i] == True: 
     element in index[i] of list letters is used 
    else: 
     element in index[i] of list numbers is used 

創建一個新的列表,例如:

new_list = [a,2,a,4,5,6] 
+1

你有問題要問? – vaultah

回答

0
numbers = [1,2,3,4,5,6] 
letters = ["a","b","a","b","c","c"] 
state = [False, False, False, False, False, False] 


choice1 = input("Enter Your 1st choice: ") 
choice2 = input("Enter Your 2nd choice: ") 

if letters[choice1] == letters[choice2]: 
    state[choice1] = (not state[choice1]) 
    state[choice2] = (not state[choice2]) 

List = [] 

print state 
for i in range(len(state)): 
    if state[i] == True: 
     List.append(letters[i]) 
    else: 
     List.append(numbers[i]) 

print List 

輸入:

Enter Your 1st choice: 0 
Enter Your 1st choice: 2 

輸出:

['a', 2, 'a', 4, 5, 6] 
0

這裏是我的解決方案:使用列表理解創建第四個列表,我將其命名爲mixed

numbers = [1, 2, 3, 4, 5, 6] 
letters = ['a', 'b', 'a', 'b', 'c', 'c'] 
states = [False, False, False, False, False, False] 

choice1 = 0 
choice2 = 2 

if letters[choice1] == letters[choice2]: 
    states[choice1] = True 
    states[choice2] = True 

mixed = [letter if use_letter else number 
     for number, letter, use_letter in zip(numbers, letters, states)] 

print numbers 
print letters 
print states 
print mixed 

輸出:

[1, 2, 3, 4, 5, 6] 
['a', 'b', 'a', 'b', 'c', 'c'] 
[True, False, True, False, False, False] 
['a', 2, 'a', 4, 5, 6] 

注意,在代碼中,我壓縮在同三個列表,並使用從states列表中的元素,從其他兩個挑的元素。此外,我將state(單數)重命名爲states(複數)以與其他列表的命名約定一致。