Python 根据输入值形成另一个列表的索引列表
斯塔克,你好 我的任务是根据初始列表和输入值形成变量索引列表:Python 根据输入值形成另一个列表的索引列表,python,python-3.x,list,Python,Python 3.x,List,斯塔克,你好 我的任务是根据初始列表和输入值形成变量索引列表: initial_list=['a', 'b', 'c'] desired_index_variable=[str(i) for i in input('Input desired indexes with space between ').split()] try: for element in initial_list: final_list=[] desired_index=final_l
initial_list=['a', 'b', 'c']
desired_index_variable=[str(i) for i in input('Input desired indexes with space between ').split()]
try:
for element in initial_list:
final_list=[]
desired_index=final_list.append(initial_list.index(element))
print (desired_index)
except ValueError:
print ('No such element in initial list')
下面是我尝试形成这种类型的列表,但结果是(我也不明白为什么有三个“非”):
然而,要求的结果是:
[0, 1]
我的新用户逻辑,我的程序非常好,但是Python说它不是,显然是(
<代码>列表。AppEng/Actudio>确实工作,并且返回<代码> No.< /代码>。
a = [1,2,3]
b = a.append(4)
print(a) # [1, 2, 3, 4]
print(b) # None
如果您不想要就地行为,您可以执行以下操作:
a = [1,2,3]
b = a+[4]
print(a) # [1, 2, 3]
print(b) # [1, 2, 3, 4]
您的代码中有几个错误
final\u列表
:final_list
设置为空列表。2.您不需要从最终的_列表中设置所需的_索引,只需直接追加即可
desired_index.append(initial_list.index(element))
所需的索引变量
。
解决所有这些问题后,以下几点对我有用:final_list.append
将始终返回None
,而不是索引为什么不在任何地方使用输入(即所需的索引变量),您能解释一下输入如何影响答案吗?我尝试了“所需的索引=final_list+[初始列表.索引(元素)]而不是“所需的索引=最终的列表.append(初始列表.索引(元素))”。结果为“[0]/[1]/[2]”,这也是不正确的(
final_list=[]
desired_index=final_list.append(initial_list.index(element))
desired_index.append(initial_list.index(element))
initial_list=['a', 'b', 'c']
desired_index_variable=[str(i) for i in input('Input desired indexes with space between ').split()]
try:
desired_index=[]
for element in desired_index_variable:
desired_index.append(initial_list.index(element))
print (desired_index)
except ValueError:
print ('No such element in initial list')