使用语法正确的打印列表"和"

时间:2015-07-10 11:46:11

标签: python string

我想以语法正确的方式打印列表,正确使用"和"在最后一个元素之前。

具体来说,我想将[1, 2, 3]之类的列表转换为字符串"1, 2, and 3"

目前,我可以这样做:

the_list = [1, 2, 3, 4]
the_list = map(str, the_list)
string = ", ".join(the_list)
comma_location = string.rfind(", ") + 1
string = string[:comma_location] + " and" + string[comma_location:]

不是有更多的Pythonic方法吗?

5 个答案:

答案 0 :(得分:2)

怎么样:

tests = [[1], [1,2], [1,2,3], ["first", "second", "third", "forth"]

for test in tests:
    print ', '.join(map(str, test[:-1])) + (' and ' if len(test) > 1 else '') + str(test[-1])

,并提供:

1
1 and 2
1, 2 and 3
first, second, third and forth

答案 1 :(得分:1)

怎么样

{{1}}

答案 2 :(得分:1)

        //original context
        OrganizationServiceContext contextORI = new OrganizationServiceContext(organisationProxy);
        //i search th team
        team team= (from k in contextORI.CreateQuery<Utilisateur>()
                            where k.Id == TEAM.Id
                            select k).FirstOrDefault();
        //i change the caller of organisationProxy
        this.organisationProxy.CallerId = team .Id;
        //i create the new context
        OrganizationServiceContext context = new OrganizationServiceContext(organisationProxy);

答案 3 :(得分:0)

由于所有列表内容都是整数,因此在进行连接之前,需要将数据类型显式转换为字符串。

>>> l = [1, 2, 3]
>>> ', '.join(map(str,l[:-1])) + ', and '+ str(l[-1])
'1, 2, and 3'
>>> 

答案 4 :(得分:0)

你可以试试这个。这应该处理the_list中有1或2个元素的情况。

the_list = [str(x) for x in the_list] 
if len(the_list)>2:
    string = ', '.join(the_list[:-1]) + ', and ' + the_list[-1]
else:
    string = the_list[0] + ' and ' + the_list[1] if len(the_list)==2 else the_list[0]

<强>输出:

>>> the_list = [1, 2, 3, 4]
>>> string
'1, 2, 3, and 4'

>>> the_list = [1, 2]
>>> string
'1 and 2'

>>> the_list = [1]
>>> string
'1'