简体   繁体   English

将列表转换为逗号分隔的字符串,在最后一项之前带有“and” - Python 2.7

[英]Converting a list into comma-separated string with “and” before the last item - Python 2.7

I have created this function to parse the list:我创建了这个函数来解析列表:

listy = ['item1', 'item2','item3','item4','item5', 'item6']


def coma(abc):
    for i in abc[0:-1]:
        print i+',',
    print "and " + abc[-1] + '.'

coma(listy)

#item1, item2, item3, item4, item5, and item6.

Is there a neater way to achieve this?有没有更简洁的方法来实现这一目标? This should be applicable to lists with any length.这应该适用于任何长度的列表。

When there are 1+ items in the list (if not, just use the first element):当列表中有 1+ 项时(如果没有,则使用第一个元素):

>>> "{} and {}".format(", ".join(listy[:-1]),  listy[-1])
'item1, item2, item3, item4, item5, and item6'

Edit: If you need an Oxford comma (didn't know it even existed!) -- just use: ", and" isntead.编辑:如果你需要一个牛津逗号(甚至不知道它存在!) - 只需使用: ", and" istead。

def oxford_comma_join(l):
    if not l:
        return ""
    elif len(l) == 1:
        return l[0]
    else:
        return ', '.join(l[:-1]) + ", and " + l[-1]

print(oxford_comma_join(['item1', 'item2', 'item3', 'item4', 'item5', 'item6']))

Output:输出:

item1, item2, item3, item4, item5, and item6

Also as an aside the Pythonic way to write另外作为 Pythonic 的写法

for i in abc[0:-1]:

is

for i in abc[:-1]:
def coma(lst):
    return '{} and {}'.format(', '.join(lst[:-1]), lst[-1])

Correction for Craig's answer above for a 2-element list (I'm not allowed to comment):更正上面 Craig 对 2 元素列表的回答(我不允许发表评论):

def oxford_comma_join(l):
    if not l:
        return ""
    elif len(l) == 1:
        return l[0]
    elif len(l) == 2:
        return l[0] + " and " + l[1]
    else:
        return ', '.join(l[:-1]) + ", and " + l[-1]

print(oxford_comma_join(['item1', 'item2', 'item3', 'item4', 'item5', 'item6']))

print(oxford_comma_join(['i1', 'i2']))

Results:结果:

item1, item2, item3, item4, item5, and item6
i1 and i2

One more different way to do:另一种不同的做法:

listy = ['item1', 'item2','item3','item4','item5', 'item6']

first way :第一种方式

print(', '.join('and, ' + listy[item] if item == len(listy)-1 else listy[item]
for item in xrange(len(listy))))

output >>> item1, item2, item3, item4, item5, and, item6

second way :第二种方式

print(', '.join(item for item in listy[:-1]), 'and', listy[-1])

output >>> (item1, item2, item3, item4, item5, 'and', 'item6')

I cannot take full credit but if you want succinct -- I modified RoadieRich's answer to use f-strings and also made it more concise.我不能完全相信,但如果你想要简洁——我修改了RoadieRich 的答案以使用f-strings并使它更简洁。 It uses the solution by RootTwo given in a comment on that answer :它使用RootTwo对该答案的评论中给出的解决方案:

def join(items):
    *start, last = items
    return f"{','.join(start)}, and {last}" if start else last

In python, many functions, that work with lists also works with iterators (like join , sum , list ).在 python 中,许多与列表一起工作的函数也与迭代器一起工作(如joinsumlist )。 To get the last item of a iterable is not that easy, because you cannot get the length, because it may be unknown in advance.获取迭代的最后一项并不是那么容易,因为你无法获取长度,因为它可能事先是未知的。

def coma_iter(iterable):
    sep = ''
    last = None
    for next in iterable:
        if last is not None:
            yield sep
            yield last
            sep = ', '
        last = next
    if sep:
        yield ', and '
    if last is not None:
        yield last

print ''.join(coma_iter(listy))

It's generally bad practice to use + when combining strings, as it is generally slow.在组合字符串时使用+通常是不好的做法,因为它通常很慢。 Instead, you can use相反,您可以使用

def comma(items):
    return "{}, and {}".format(", ".join(items[:-1]), items[-1])

You should note, however, that this will break if you only have one item:但是,您应该注意,如果您只有一项,这将中断:

>>> comma(["spam"])
', and spam'

To solve that, you can either test the length of the list ( if len(items) >= 2: ), or do this, which (imho) is slightly more pythonic:为了解决这个问题,你可以测试列表的长度( if len(items) >= 2: ),或者这样做,这(恕我直言)稍微更像pythonic:

def comma(items):
    start, last = items[:-1], items[-1]

    if start:
        return "{}, and {}".format(", ".join(start), last)
    else:
        return last

As we saw above, a single item list will result in an empty value for items[:-1] .正如我们在上面看到的,单个项目列表将导致items[:-1]为空值。 if last: is just a pythonic way of checking if last is empty. if last:只是检查last是否为空的 Pythonic 方式。

Might as well round out the solutions with a recursive example.不妨用递归示例来完善解决方案。

>>> listy = ['item1', 'item2','item3','item4','item5', 'item6']
>>> def foo(a):
    if len(a) == 1:
        return ', and ' + a[0]
    return a[0] + ', ' + foo(a[1:])

>>> foo(listy)
'item1, item2, item3, item4, item5, , and item6'
>>> 

You can also try the quoter library您也可以尝试quoter

>>> import quoter
>>> mylist = ['a', 'b', 'c']
>>> quoter.and_join(mylist)
'a, b, and c'
>>> quoter.or_join(mylist)
'a, b, or c'

https://pypi.python.org/pypi/quoter https://pypi.python.org/pypi/quoter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 省略以逗号分隔的列表中的最后一个元素 - Omit last element in comma-separated list 一个 function 接受一个列表值并返回一个字符串,其中所有项目由逗号和空格分隔,并插入最后一项之前 - a function that takes a list value and returns a string with all the items separated by a comma and a space, with and inserted before the last item 在熊猫数据框中以逗号分隔的字符串中的每一项添加+1 - Add +1 to each item in a comma-separated string in pandas dataframe 分割逗号分隔的字符串 - Splitting a comma-separated string 如何将包含未用逗号分隔的值列表的字符串转换为列表? - How to convert a string containing a list of values that are not comma-separated to a list? Python用于过滤另一个csv列表上以逗号分隔的列表 - Python to filter a comma-separated list on another csv list Pythonic将整数列表转换为逗号分隔范围字符串的方法 - Pythonic way to convert a list of integers into a string of comma-separated ranges 将一串逗号分隔的整数解析为整数列表的“pythonic”方法? - "pythonic" method to parse a string of comma-separated integers into a list of integers? 如何将逗号分隔的字符串拆分为字符串列表? - How to split a comma-separated string into a list of strings? 在python列表中选择一个没有逗号分隔的元素 - select an element in a python list without comma-separated
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM