根据第三个列表中的索引返回,从2个列表创建新列表

时间:2015-11-01 15:58:02

标签: python list python-3.x

说我有以下列表(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和a(索引0和2),则对于所述位置,列表状态必须从False变为True。之后,它应该根据新的状态列表创建一个新列表,如果状态中的元素为False,则从数字中获取索引项,如果状态为true,则从列表字母中获取索引项:

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]

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分:0)

这是我的解决方案:使用list comprehension创建第四个列表,我将其命名为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(复数)以与其他列表的命名约定一致。