gpt4 book ai didi

python - 列表理解中的临时变量

转载 作者:太空狗 更新时间:2023-10-29 17:31:59 27 4
gpt4 key购买 nike

我经常遇到这样一段代码。

raw_data  = [(s.split(',')[0], s.split(',')[1]) for s in all_lines if s.split(',')[1] != '"NaN"']

基本上,我想知道是否有一种方法可以创建一个像 splitted_s 这样的临时变量,以避免必须对循环对象重复操作(比如,在这种情况下,有将其拆分三份)。

最佳答案

如果你有两个要处理的 Action ,你可以嵌入另一个列表理解:

raw_data  = [(lhs, rhs) 
for lhs, rhs
in [s.split(',')[:2] for s in all_lines]
if rhs != '"NaN"']

您可以在内部使用生成器(它也提供了一个小的性能增益):

            in (s.split(',')[:2] for s in all_lines)

它甚至会比您的实现更快:

import timeit

setup = '''import random, string;
all_lines = [','.join((random.choice(string.letters),
str(random.random() if random.random() > 0.3 else '"NaN"')))
for i in range(10000)]'''
oneloop = '''[(s.split(',')[0], s.split(',')[1])
for s in all_lines if s.split(',')[1] != '"NaN"']'''
twoloops = '''raw_data = [(lhs, rhs)
for lhs, rhs
in [s.split(',') for s in all_lines]
if rhs != '"NaN"']'''

timeit.timeit(oneloop, setup, number=1000) # 7.77 secs
timeit.timeit(twoloops, setup, number=1000) # 4.68 secs

关于python - 列表理解中的临时变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29820026/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com