在列表中更具Python风格地迭代包含的元组。

huangapple go评论60阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月12日 20:57:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76456895.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定