确定列表中的项是否是lis中的最后一项

2024-04-25 23:31:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数printListAsSentence(l),其中l应该是list。此函数应打印列表中以逗号分隔的项目,除非它是列表中的最后一个项目,否则应以句点结束。我原以为我可以用l[-1],但那不管用。以下是我的尝试:

def printListAsSentence(l):
    for item in l:
        if item == l[-1]: #This compares the value of the strings. Only will work if there is no duplicate values.
            print(item + ".", end="")
        else:
            print(item + ",", end="")

举个例子:

names = ['rob', 'jack', 'rob']
printListAsSentence(names)

将输出:

"rob.jack,rob."

Tags: the项目函数列表ifnamesitemlist
3条回答

或许可以使用join

names=['rob', 'jack', 'rob']
','.join(names) + '.'
# 'rob,jack,rob.'

如果列表中的最后一个项有重复项,则您的尝试无效,因为您检查的是该项的值,而不是它在列表中的实际位置。您可以使用enumerate()来获取项目的索引及其值。你知道吗

for index, item in enumerate(l):
    if index = len(l)-1:
        print(item + ".", end="")
    else:
        print(item + ",", end="")

但是使用join的其他建议是更具脓性的解决方案。你知道吗

您可以使用join在每个字符串之间放置一个,,然后仅连接最后一个点:

print(",".join(l) + ".")

如果确实要手动循环,一种方法是使用enumerate

for index, item in enumerate(l):
    if index == len(l)-1:
        # this is the last item
    else:
        # it's not the last item

相关问题 更多 >

    热门问题