简体   繁体   English

如何使用列表理解删除列表中列表中的项目

[英]How to remove item in list in list with list comprehension

I have a large list like this: 我有很多这样的清单:

mylist = [['pears','apples','40'],['grapes','trees','90','bears']]

I'm trying to remove all numbers within the lists of this list. 我正在尝试删除此列表中的所有数字。 So I made a list of numbers as strings from 1 to 100: 所以我列出了从1到100的数字作为字符串:

def integers(a, b):
         return list(range(a, b+1))

numb = integers(1,100)

numbs = []
for i in range(len(numb)):
    numbs.append(str(numb[i])) # strings

numbs = ['1','2',....'100']

How can I iterate through lists in mylist and remove the numbers in numbs ? 我怎样才能通过列出迭代mylist和删除的数字numbs Can I use list comprehension in this case? 在这种情况下,我可以使用列表理解吗?

如果数字始终在子列表的最后

mylist = [ x[:-1] for x in mylist ]

mylist = [[item for item in sublist if item not in numbs] for sublist in mylist] should do the trick. mylist = [[item for item in sublist if item not in numbs] for sublist in mylist]应该可以解决。

However, this isn't quite what you've asked. 然而,这是不是你问什么相当 Nothing was actually removed from mylist , we've just built an entirely new list and reassigned it to mylist . 实际上,什么都没有从mylist删除,我们刚刚建立了一个全新的列表并将其重新分配给mylist Same logical result, though. 逻辑结果相同。

If numbers are always at the end and only once, you can remove the last item like: 如果数字始终在结尾并且只有一次,则可以删除最后一项,例如:

my_new_list = [x[:-1] for x in mylist]

If there is more (of if they are not ordered), you have to loop thru each elements, in that case you can use: 如果还有更多(如果没有排序的话),则必须遍历每个元素,在这种情况下,您可以使用:

my_new_list = [[elem for elem in x if elem not in integer_list] for x in mylist]

I would also recommend to generate the list of interger as follow : 我还建议生成如下的整数列表:

integer_list = list(map(str, range(1, 100)))

I hope it helps :) 希望对您有所帮助:)

Instead of enumerating all the integers you want to filter out you can use the isdigit to test each string to see if it really is only numbers: 无需枚举要过滤的所有整数,可以使用isdigit测试每个字符串以查看它是否仅是数字:

mylist = [['pears','apples','40'],['grapes','trees','90','bears']]
mylist2 = [[x for x in aList if not x.isdigit()] for aList in mylist]
print mylist2
[['pears', 'apples'], ['grapes', 'trees', 'bears']]

If you have the following list: 如果您有以下列表:

mylist = [['pears','apples','40'],['grapes','trees','90','bears']]
numbs = [str(i) for i in range(1, 100)]

Using list comprehension to remove element in numbs 使用列表numbs删除numbs元素

[[l for l in ls if l not in numbs] for ls in mylist]

This is a more general way to remove digit elements in a list 这是删除列表中数字元素的更通用方法

[[l for l in ls if not l.isdigit()] for ls in mylist]

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

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