Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的语法列表连接_Python_List - Fatal编程技术网

Python中的语法列表连接

Python中的语法列表连接,python,list,Python,List,除了最后一个使用“and”的项目外,什么是连接列表以便在每个项目之间都有逗号的最通俗的方式 基于评论的修复导致了这种有趣的方式。它假设要联接的列表的字符串条目中没有逗号(这无论如何都会有问题,所以这是一个合理的假设) 只是特例,最后一个。大概是这样的: '%s and %s'%(', '.join(mylist[:-1]),mylist[-1]) 可能不会有更简洁的方法了 这在零情况下也会失败。尝试此方法,它会考虑边缘情况,并使用格式(),显示另一种可能的解决方案: def my_join(l

除了最后一个使用“and”的项目外,什么是连接列表以便在每个项目之间都有逗号的最通俗的方式


基于评论的修复导致了这种有趣的方式。它假设要联接的列表的字符串条目中没有逗号(这无论如何都会有问题,所以这是一个合理的假设)


只是特例,最后一个。大概是这样的:

'%s and %s'%(', '.join(mylist[:-1]),mylist[-1])
可能不会有更简洁的方法了


这在零情况下也会失败。

尝试此方法,它会考虑边缘情况,并使用
格式()
,显示另一种可能的解决方案:

def my_join(lst):
    if not lst:
        return ""
    elif len(lst) == 1:
        return str(lst[0])
    return "{} and {}".format(", ".join(lst[:-1]), lst[-1])
按预期工作:

 my_join([])
=> ""
 my_join(["x"])
=> "x"
 my_join(["x", "y"])
=> "x and y"
 my_join(["x", "y", "z"])
=> "x, y and z"

此表达式用于:

print ", ".join(data[:-2] + [" and ".join(data[-2:])])
如图所示:

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

已经有很好的答案了。这一个在所有测试用例中都有效,并且与其他一些测试用例略有不同

def grammar_join(words):
    return reduce(lambda x, y: x and x + ' and ' + y or y,
                 (', '.join(words[:-1]), words[-1])) if words else ''

tests = ([], ['a'], ['a', 'b'], ['a', 'b', 'c'])
for test in tests:                                 
    print grammar_join(test)


如果您需要不支持负索引的解决方案(即Django QuerySet)

def牛津大学联合(字符串列表):
如果len(字符串列表)<1:
文本=“”
elif len(字符串列表)=1:
text=string\u列表[0]
elif len(字符串列表)=2:
text='and'.join(字符串列表)
其他:
text=',join(字符串列表)
text='{parts[0]}和{parts[2]}'。格式(parts=text.rpartition(','))#
返回文本
牛津大学(苹果、橘子、芒果)

special_-join([“foo”])
返回
'和foo'
..@chepner:“在Python文化中,把某些东西描述成聪明的东西并不被认为是一种恭维。”;)即使这样也太简洁了,因为它假设了2个或更多项。为什么使用“e代表e in”语法?我甚至不认为这是必要的;你说得对。我在玩别的东西,但我最终得到的东西不需要生成器理解部分。修正。+1用于将最后两个与“和”连接在一起,然后再与“,”连接。接受此答案是因为它简洁且无需假设。没有其他答案那么“聪明”,因此是最“python”的解决方案。唯一的一点是,我也会在第二个分支中使用
format
,因此乐趣总是返回一个字符串。@thg435我更喜欢可读性而不是“smartness”:)对于第二个分支,一个简单的
str()
就可以+1,因为它不想像其他分支一样聪明。。。这是非常令人沮丧的,在代码中运行,比如当前最上等的答案,但后来发现它有一个bug没有立即被注意到,因为测试用例函数的聪明度+1。谁关心牛津逗号?这个问题和答案不使用。有关使用牛津逗号的问题和答案,请参见。如果列表中的项目包含逗号,请参见。
>>> 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
def grammar_join(words):
    return reduce(lambda x, y: x and x + ' and ' + y or y,
                 (', '.join(words[:-1]), words[-1])) if words else ''

tests = ([], ['a'], ['a', 'b'], ['a', 'b', 'c'])
for test in tests:                                 
    print grammar_join(test)
a
a and b
a, b and c
def oxford_join(string_list):
    if len(string_list) < 1:
        text = ''
    elif len(string_list) == 1:
        text = string_list[0]
    elif len(string_list) == 2:
        text = ' and '.join(string_list)
    else:
        text = ', '.join(string_list)
        text = '{parts[0]}, and {parts[2]}'.format(parts=text.rpartition(', '))  # oxford comma
    return text

oxford_join(['Apples', 'Oranges', 'Mangoes'])