语法列表加入Python

use*_*170 25 python list

加入列表的最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)

  • +1 用于在用“,”进行一般连接之前用“and”连接最后两个。 (2认同)

Ó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)

  • 不像其他答案那么“聪明”,因此是最“Pythonic”的解决方案。唯一的一点是,我也会在第二个分支中使用“format”,以便 fun 始终返回一个字符串。 (2认同)

ely*_*ely 5

基于评论的修复导致了这种有趣的方式.它假定要加入的列表的字符串条目中不会出现逗号(无论如何都会出现问题,因此这是一个合理的假设.)

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)

  • `special_join(["foo"])`返回`'和foo'`... (6认同)
  • @chepner:"用巧妙的方式描述一些东西并不是Python文化中的恭维." ;) (2认同)