[英]If a certain word is not before the search word then add to list python
[英]How to add a word before the last word in list?
您好,我是这种编程语言的新手
我想在列表的最后一项之前加上'and'
一词。
例如:
myList = [1,2,3,4]
如果我打印它,输出必须像:
1,2,3 and 4
这是一种方法,但是我必须将int转换为字符串才能使用join
:
myList = [1,2,3,4]
smyList = [str(n) for n in myList[:-1]]
print(",".join(smyList), 'and', myList[-1])
给出:
1,2,3 and 4
列表的-1
索引给出最后(最右边)的元素。
这可能不是最优雅的解决方案,但这就是我要解决的方法。
定义格式化程序功能,如下所示:
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
然后这样称呼它
>>> x = [1,2,3,4]
>>> format_list(x)
1, 2, 3, and 4
您还可以使用字符串格式:
l = [1,2,3,4]
print("{} and {}".format(",".join(str(i) for i in l[:-1]), l[-1]))
#'1,2,3 and 4'
使用join
(连接列表元素)和map(str,myList)
将列表中的所有整数转换为字符串
','.join(map(str,myList[:-1])) + ' and ' + str(myList[-1])
#'1,2,3 and 4'
如果您说的是“如何在列表中的最后一个单词之前添加单词”,那么您的问题将产生误导。 这意味着您想在列表中的最后一项之前添加“ and”字符串,而许多人使用.format()方法给出答案时,您应该在打印时或列表中指定要使用“ and”以进一步使用该结果:
这是根据您的问题列出的方法:
myList = [1,2,3,4]
print(list((lambda x,y:(x+['and']+y))(myList[:-1],myList[-1:])))
输出:
[1, 2, 3, 'and', 4]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.