简体   繁体   English

如何在列表中的最后一个单词之前添加单词?

[英]How to add a word before the last word in list?

Hello I'm new to this programming language 您好,我是这种编程语言的新手

I wanted to add the word 'and' before the last item in my list. 我想在列表的最后一项之前加上'and'一词。

For example: 例如:

myList = [1,2,3,4]

If I print it the output must be like: 如果我打印它,输出必须像:

1,2,3 and 4

Here is one way, but I have to convert the int's to strings to use join : 这是一种方法,但是我必须将int转换为字符串才能使用join

myList = [1,2,3,4]
smyList = [str(n) for n in myList[:-1]]   
print(",".join(smyList), 'and', myList[-1])

gives: 给出:

1,2,3 and 4

The -1 index to the list gives the last (rightmost) element. 列表的-1索引给出最后(最右边)的元素。

This may not be the most elegant solution, but this is how I would tackle it. 这可能不是最优雅的解决方案,但这就是我要解决的方法。

define a formatter function as follows: 定义格式化程序功能,如下所示:

def format_list(mylist)
    str = ''
    for i in range(len(mylist)-1):
        str.append(str(mylist[i-1]) + ', ')

    str.append('and ' + str(mylist[-1]))

    return str

then call it like this 然后这样称呼它

>>> x = [1,2,3,4]
>>> format_list(x)
1, 2, 3, and 4

You can also use string formating: 您还可以使用字符串格式:

l = [1,2,3,4]
print("{} and {}".format(",".join(str(i) for i in l[:-1]), l[-1]))
#'1,2,3 and 4'

Using join (to join list elements) and map(str,myList) to convert all integers inside list to strings 使用join (连接列表元素)和map(str,myList)将列表中的所有整数转换为字符串

','.join(map(str,myList[:-1])) + ' and ' + str(myList[-1])
#'1,2,3 and 4'

Your question is misleading, if you are saying "How to add a word before the last word in list?" 如果您说的是“如何在列表中的最后一个单词之前添加单词”,那么您的问题将产生误导。 it means you want to add 'and' string before last item in the list , while many people are giving answer using .format() method , You should specify you want 'and' for printing or in list for further use of that result : 这意味着您想在列表中的最后一项之前添加“ and”字符串,而许多人使用.format()方法给出答案时,您应该在打印时或列表中指定要使用“ and”以进一步使用该结果:

Here is list method according to your question : 这是根据您的问题列出的方法:

myList = [1,2,3,4]
print(list((lambda x,y:(x+['and']+y))(myList[:-1],myList[-1:])))

output: 输出:

[1, 2, 3, 'and', 4]

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM