简体   繁体   English

删除列表中的数字的倍数:

[英]Removal of multiples of a number on a list:

我有两个,我有这个列表,我将如何从该列表中删除数字2的倍数并更新它?

10 [2, 3, 4, 5, 6, 7, 8, 9, 10] 2

Assuming you have a list l and a number n you can remove all multiples of n from l with a list comprehension: 假设您有一个列表l和一个数字n您可以使用列表解析从l删除所有n倍数:

l = [i for i in l if i%n]

writing if i%n here is the same as writing if i%n != 0 , and n divides i iff i%n==0 if i%n在这里与写if i%n != 0 ,并且n除以i iff i%n==0

Methods: 方法:

Using a generator 使用发电机

One of the first option that comes to mind is to make use of a generator. 想到的第一个选择之一是使用发电机。 The generator would iterate through a sequence, and test if the current element is divisible by n . 生成器将迭代序列,并测试当前元素是否可被n整除。 This allows you to have a more generic solution as well: 这使您可以获得更通用的解决方案:

def filter_by_multiple(seq, n):
    for i in seq:
        if i % n:
            yield i

Usage: 用法:

>>> filter_by_multiple([2, 3, 4, 5, 6, 7, 8, 9, 10], 2)
<generator object filter_by_multiple at 0x000000374ED30258>
>>> list(filter_by_multiple([2, 3, 4, 5, 6, 7, 8, 9, 10], 2))
[3, 5, 7, 9]
>>> 

Using a generator expression 使用生成器表达式

While the above solution is fine, is can be shortened even more by using generator expressions . 虽然上述解决方案很好,但使用生成器表达式可以进一步缩短。 generator expression are like list comprehensions, but unlike them, they return a generator iterator instead of a list. 生成器表达式与列表推导类似,但与它们不同,它们返回生成器迭代器而不是列表。

Usage: 用法:

>>> l = [2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(el for el in l if el % 2)
[3, 5, 7, 9]
>>> 

Using filter() : 使用 filter()

Among many of the builtin functions in Python, there is one for filtering list called filter() . 在Python的许多内置函数中,有一个用于过滤列表,名为filter() The usually way to use filter() is to pass in the function you want to use to filter your list, and then the actual list you want filtered. 使用filter()的常用方法是传入要用于过滤列表的函数,然后传递要过滤的实际列表。 In your case, you want to filter out every element the is not a multiple of two: 在您的情况下,您希望过滤掉不是两个的倍数的每个元素:

Usage: 用法:

>>> l = [2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(filter(lambda x: x % 2, l))
[3, 5, 7, 9]
>>> 

Using a list comprehension 使用列表理解

While all of the above are fine ways for filtering a list, probably the most obvious and canonical, is to use a list comprehension. 虽然以上所有都是过滤列表的好方法,但最明显和规范的可能是使用列表理解。 In your case, your list comprehension, is dead simple. 在你的情况下,你的列表理解,很简单。

Usage: 用法:

>>> l = [2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [el for el in l if el % 2]
[3, 5, 7, 9]
>>>

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

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