I have initial_list=['a', 'b с', 'c']
, which is written below. After that, I need to input two values and search for their indexes. For example, I need to input a,b c
and got [0, 1]
list. But there are some difficulties.
这是我的代码:
initial_list=['a', 'b с', 'c']
new_list=[]
new_list2=[]
for elem in initial_list:
new_list.append(elem)
if (' ') in elem:
new_list.remove(elem)
newelem=(f'{elem[0]}{elem[2]}')
new_list.append(newelem)
print(new_list) #PRINT #1
desired_index_variable=[str(i) for i in input('Input desired indexes with comma between(NO SPACE AFTER COMMA) ').split(',')]
for elem in desired_index_variable:
new_list2.append(elem)
if (' ') in elem:
new_list2.remove(elem)
newelem=(f'{elem[0]}{elem[2]}')
new_list2.append(newelem)
print (new_list2) #PRINT #2
try:
desired_index=[]
for element in new_list2:
desired_index.append(initial_list.index(new_list))
print (desired_index) #PRINT #3
except ValueError:
print ('No such element in initial list')
该程序的工作原理是:
>>['a', 'bс', 'c']
>>Input desired indexes with comma between(NO SPACE AFTER COMMA) a,b c
>>['a', 'bc']
>>No such element in initial list
So I did a joining of b c
: the result of PRINT#1 is :['a', 'bс', 'c']
After that I did joining of input values a,b c
: >>['a', 'bc']
But the result is not the [0, 1]
, but No such element in initial list
我在哪里错过寻找正确索引的最后一步?