[英]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.