英文:
Iterate included tuples in list more pythonic
问题
我有这个循环。有没有更聪明的方法?
example = [('tes1', 'test2'), ('test3', 'test4')]
string = ''
for i, tuple in enumerate(example):
string = string + ' '.join(tuple)
if i != len(example) - 1:
string += ', '
print(string)
我考虑使用.join()来完成,但不知道如何做。
英文:
I have this loop. Is there smarter way to this?
example = [('tes1', 'test2'), ('test3', 'test4')]
string = ''
for i, tuple in enumerate(example):
string = string + ' '.join(tuple)
if i != len(example) - 1:
string += ', '
print(string)
I thinking about make it by .join(), but can't figure out how.
答案1
得分: 3
你可以在列表推导式中使用 f-string,然后连接结果。
example = [('tes1', 'test2'), ('test3', 'test4')]
string = ', '.join(f'{x} {y}' for x, y in example)
英文:
You could use an f-string in a list comprehension and then join the result
example = [('tes1', 'test2'), ('test3', 'test4')]
string = ', '.join(f'{x} {y}' for x, y in example)
答案2
得分: 2
可以使用以下方法来实现:
string = ', '.join([' '.join(t) for t in example])
英文:
Yes, you can do it using the following:
string = ', '.join([' '.join(t) for t in example])
答案3
得分: 1
你可以使用连接操作来表达它:
example = [('tes1', 'test2'), ('test3', 'test4')]
string = ', '.join(map(' '.join, example))
print(string)
英文:
With joins, you could express it like:
example = [('tes1', 'test2'), ('test3', 'test4')]
string = ', '.join(map(' '.join, example))
print(string)
答案4
得分: 1
可以这样做:
示例 = [('tes1', 'test2', 'test'), ('test3', 'test4')]
字符串 = ', '.join(' '.join(t) for t in 示例)
print(字符串)
不需要使用列表推导;可以使用生成器来实现。
英文:
you can do:
example = [('tes1', 'test2', 'test'), ('test3', 'test4')]
string = ', '.join(' '.join(t) for t in example)
print(string)
No need for list comprehension; you can do with generator
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论