加入列表的最pythonic方式是什么,以便每个项目之间都有逗号,除了使用"和"的最后一个?
["foo"] --> "foo"
["foo","bar"] --> "foo and bar"
["foo","bar","baz"] --> "foo, bar and baz"
["foo","bar","baz","bah"] --> "foo, bar, baz and bah"
Run Code Online (Sandbox Code Playgroud)
Mat*_*son 27
这个表达式做到了:
print ", ".join(data[:-2] + [" and ".join(data[-2:])])
Run Code Online (Sandbox Code Playgroud)
如下所示:
>>> data
['foo', 'bar', 'baaz', 'bah']
>>> while data:
... print ", ".join(data[:-2] + [" and ".join(data[-2:])])
... data.pop()
...
foo, bar, baaz and bah
foo, bar and baaz
foo and bar
foo
Run Code Online (Sandbox Code Playgroud)
Ósc*_*pez 14
试试这个,它考虑了边缘情况和用途format(),以显示另一种可能的解决方案:
def my_join(lst):
if not lst:
return ""
elif len(lst) == 1:
return str(lst[0])
return "{} and {}".format(", ".join(lst[:-1]), lst[-1])
Run Code Online (Sandbox Code Playgroud)
按预期工作:
my_join([])
=> ""
my_join(["x"])
=> "x"
my_join(["x", "y"])
=> "x and y"
my_join(["x", "y", "z"])
=> "x, y and z"
Run Code Online (Sandbox Code Playgroud)
基于评论的修复导致了这种有趣的方式.它假定要加入的列表的字符串条目中不会出现逗号(无论如何都会出现问题,因此这是一个合理的假设.)
def special_join(my_list):
return ", ".join(my_list)[::-1].replace(",", "dna ", 1)[::-1]
In [50]: def special_join(my_list):
return ", ".join(my_list)[::-1].replace(",", "dna ", 1)[::-1]
....:
In [51]: special_join(["foo", "bar", "baz", "bah"])
Out[51]: 'foo, bar, baz and bah'
In [52]: special_join(["foo"])
Out[52]: 'foo'
In [53]: special_join(["foo", "bar"])
Out[53]: 'foo and bar'
Run Code Online (Sandbox Code Playgroud)