简体   繁体   English

Python从列表中删除项目,其中仅部分项目已知

[英]Python remove item from list where only part of item is known

I have a list of things like this: 我有这样的事情清单:

My_list = [['A1'],['B2'],['C3']]

I am asking the user to enter a LETTER (only) indicating which element to delete. 我要求用户输入一个LETTER(仅),该字母表示要删除的元素。 So, for example, if the user entered 'B', the 2nd entry should be deleted and the list should look like this: 因此,例如,如果用户输入“ B”,则应删除第二个条目,并且列表应如下所示:

My_list = [['A1'],['C3']]

I have tried several solutions, but below is my best attempt at this...and i believe i'm not too far away from the final answer. 我已经尝试了几种解决方案,但是下面是我在这方面的最佳尝试……我相信我离最终答案不太远。

My_list = [['A1','B2','C3']]

print('What LETTER pairing would you like to delete?')
get_letter = input()
delete_letter = get_letter.upper()

for each_element in My_list:
    for each_pair in each_element:
        if each_pair[0] == delete_letter:
            location = My_list.index(each_pair)
            clues_list.pop(location)
            print('done')

when i run and enter 'B' the Compile error says... 当我运行并输入'B'时,编译错误提示...

ValueError: 'B2' is not in list

...but B2 is in list! ...但是B2在列表中!

Where am i going wrong? 我要去哪里错了?

The error message is correct: 'B2' is not in My_list , although ['B2'] is! 错误消息是正确的: 'B2' 不在 My_list ,尽管['B2']是!

You need to remove each_element , not each_pair , and should not do so while iterating over the list. 您需要删除each_element ,而不是each_pair ,并且在遍历列表时不应这样做。 For example, try: 例如,尝试:

location = None
for index, each_element in enumerate(My_list):
    for each_pair in each_element:
        if each_pair[0] == delete_letter:
            location = index
            break
if location is not None:
    My_list.pop(location)

However, it seems likely that a different data structure would be more useful to you, eg a dictionary: 但是,似乎不同的数据结构对您更有用,例如字典:

data = {'A': 1, 'B': 2, 'C': 3}

where the code becomes as simple as: 代码变得如此简单:

if delete_letter in data: 
    del data[delete_letter]

You can have it done in a much more concise way (using list comprehension ): 您可以用更简洁的方式(使用列表推导 )来完成它:

My_list = [['A1','B2','C3']]

get_letter = raw_input('What LETTER pairing would you like to delete? ')
delete_letter = get_letter.upper()
print delete_letter
new_list = [var for var in My_list[0] if delete_letter not in var]
print new_list

A few caveats: not in will try to find delete_letter anywhere in the variable, so if you want it to have more exact matches you can look into .startswith . 注意事项: not in会尝试在变量的任何位置找到delete_letter ,因此,如果您希望它具有更精确的匹配项,则可以查看.startswith Then, my piece of code blindly follows your list of lists. 然后,我的一段代码盲目地跟随您的列表列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM