简体   繁体   English

将 function 应用于列表的某些项目的最pythonic方法是什么?

[英]What is the most pythonic way to apply function to some items of a list?

Let's take this code that prints all positive integer of a list:让我们使用这段代码打印列表的所有正面 integer :

l = [1, -1, 1, 0, 2]
for i in l:
   if i > 0:
       print(i)

I can do it with a list comprehension but I guess this has the disadvantage to create a new useless list:我可以通过列表理解来做到这一点,但我想这对创建一个新的无用列表有不利之处:

[print(i) for i in l if i > 0]

So my question: is there a more pythonic way to write this?所以我的问题是:有没有更 Pythonic 的方式来写这个?

The plain for-loop is perfectly Pythonic.普通的 for 循环是完全 Pythonic 的。 You want to loop over the elements of the list, select the ones that are greater than zero, and print them, and that's exactly what it does - no more, no less.您想遍历列表的元素 select 大于零的元素,然后打印它们,这正是它所做的 - 不多也不少。

The list comprehension is not Pythonic , mostly for the reason you gave: it creates a new useless list.列表理解不是 Pythonic ,主要是因为您给出的原因:它创建了一个新的无用列表。 Even if you were going to use the list , using a list comprehension for side effects is still bad practice. 即使您打算使用 list ,使用列表推导来处理副作用仍然是不好的做法。

The most Pythonic way to apply a function to some subset of a list of elements is to use a for loop, just as you already have.将 function 应用于元素列表的某个子集的最 Pythonic 方法是使用for循环,就像您已经拥有的一样。

Within that for loop, there is an argument to be made for filtering the list before assigning any value to i ;在那个for循环中,在将任何值分配给i之前,有一个参数用于过滤列表; whether that constitutes an improvement is usually a matter of opinion and will depend on the context.这是否构成改进通常是一个见仁见智的问题,将取决于具体情况。

for i in filter(lambda x: x > 0, l):
    print(i)

In this case, I think it's worse.在这种情况下,我认为情况更糟。 But sometimes you have a predicate at hand, and filtering can be syntactically lighter.但有时你手头有一个谓词,过滤在语法上可以更轻松。 Compare相比

for i in some_list_of_strings:
    if i.isdigit():
        print(i)

with

for i in filter(str.isdigit, some_list_of_strings):
    print(i)

I suppose that theoretically you could contrive to use a generator comprehension in order to avoid creating a large list in memory:我想理论上你可以设法使用生成器理解以避免在 memory 中创建一个大列表:

for _ in (print(i) for i in l if i > 0): pass

(maybe also using some function that does the consuming of values from the generator, so that any loop is hidden away inside that function). (也许还使用一些 function 来消耗来自生成器的值,因此任何循环都隐藏在该函数内)。

However, not only is this less readable than the explicit for loop, the plain for loop is also quicker.但是,这不仅比显式for循环可读性差,而且纯for循环也更快。

import time

l = [1, -1, 1, 0, 2]

# we don't really want lots of output for this timing test
def dont_really_print(i):
    return i

t1 = time.time()

for x in range(1000000):
    for i in l:
        if i > 0:
            dont_really_print(i)

t2 = time.time()

for x in range(1000000):
    for _ in (dont_really_print(i) for i in l if i > 0):
        pass

t3 = time.time()

print(f"generator comprehension {t3 - t2:.3f} "
      f"explicit loop {t2 - t1:.3f}")

gives:给出:

generator comprehension 0.629 explicit loop 0.423

Generally, whether Python or any other language, what you want to do is known as a "map."通常,无论是 Python 还是其他任何语言,您要做的事情都称为“地图”。

Print is a weird function to map, so here's another function for better demonstration purposes.打印是一个奇怪的 function 到 map,所以这里是另一个 function 用于更好的演示目的。

def add_one(num):
    return num + 1

foo = [1, 2, 3, 4]
new_list = map(add_one, foo)
print(list(new_list))

You can typically map in parallel, sometimes asynchronously, and a good number of parallel processing paradigms (including Python's multiprocessing) use map as a fundamental operation for using multiple cores to implement a function.您通常可以并行使用 map,有时是异步的,并且大量并行处理范例(包括 Python 的多处理)使用 map 作为使用多核实现 ZC1C425268E68385D1AB5074C14 的基本操作。

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

相关问题 应用函数和返回多列的最pythonic方法是什么? - What is the most pythonic way to apply a function on and return multiple columns? 从 OrderedDict 列表中查找项目的最pythonic 方法是什么? - what would be the most pythonic way of finding items from a list of OrderedDict? 修改函数函数的最Pythonic方法是什么? - What is the most Pythonic way to modify the function of a function? 列表边界-最Python的方式是什么? - List boundaries - what is the most Pythonic way? 在此函数中传递kwargs的最pythonic方法是什么? - What is the most pythonic way to pass kwargs in this function? 什么是有条件地返回函数的最pythonic方式 - What is the most pythonic way to conditionally return a function 在具有多种类型的空白字符的字符串中的每个单词上应用函数的最有效的方法是什么? - What's the most pythonic way to apply a function on every word in a string with multiple types of white space characters? 将函数递归应用于字符串值的最pythonic方法 - Most pythonic way to recursively apply a function to string values 大多数Pythonic方法在O(1)复杂度的列表中查找/检查项目? - Most Pythonic way to find/check items in a list with O(1) complexity? 获得有序的独特项目列表的最佳/最pythonic方式 - Best / most pythonic way to get an ordered list of unique items
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM