简体   繁体   English

迭代列表并为每个值创建一个元组的 Pythonic 方法

[英]Pythonic way to iterate over list and create a tuple with each value

So I have this list:所以我有这个清单:

['test.csv', 'test2.csv']

I need it to have its final form like this:我需要它的最终形式是这样的:

[('test.csv', 'test.csv'),('test2.csv', 'test2.csv')]

What would be the best way, performance wise, to do this in Python?在性能方面,在 Python 中执行此操作的最佳方法是什么?

Thanks.谢谢。

You are looking forlist comprehension .您正在寻找列表理解

Try this:尝试这个:

files = ['test.csv', 'test2.csv']
result = [(file, file) for file in files]

I'd zip:我会 zip:

[*zip(lst, lst)]

Benchmark on list(map(str, range(1000))) : list(map(str, range(1000)))上的基准测试:

 28 us  [*zip(lst, lst)]
 44 us  [(file, file) for file in files]
 89 us  [(file,) * 2 for file in files]
259 us  list(map(lambda x: tuple([x] * 2), lst))

Or for repeating each value 10 instead of 2 times (just because someone proposed generalizing like that... I don't think it's something you'd realistically do... already your duplication is an odd thing to do):或者将每个值重复 10 次而不是 2 次(只是因为有人提出这样的概括......我不认为这是你实际要做的事情......你的重复已经是一件奇怪的事情了):

 67 us  [*zip(*[lst] * 10)]
115 us  [(file,) * 10 for file in files]
287 us  list(map(lambda x: tuple([x] * 10), lst))

Code ( Try it online! ):代码( 在线试用! ):

from timeit import repeat

setup = '''
lst = files = list(map(str, range(1000)))
'''
codes = '''
[*zip(lst, lst)]
[(file, file) for file in files]
[(file,) * 2 for file in files]
list(map(lambda x: tuple([x] * 2), lst))
'''.strip().splitlines()

for _ in range(3):
    for code in codes:
        t = min(repeat(code, setup, number=1000))
        print('%3d us ' % (t * 1e3), code)
    print()

Generic version of @grfreitas answer. @grfreitas 答案的通用版本。

num_times_to_duplicate = 2
files = ["test.csv", "test2.csv"]
result = [(file,) * num_times_to_duplicate for file in files]
print(result)

You can use map您可以使用map

lst = ['test.csv', 'test2.csv']
lst = list(map(lambda x: tuple([x] * 2), lst))
print(lst) # [('test.csv', 'test.csv'), ('test2.csv', 'test2.csv')]

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

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