【问题标题】:How to determine if item is last item in a set如何确定项目是否是集合中的最后一个项目
【发布时间】:2022-01-06 15:24:00
【问题描述】:

我在一个集合中有任意数量的项目。

当我在集合的最后一项时,我想做一些不同的事情 - 是否可以这样做而不必找到集合的长度并有一个计数器变量?

    for e in elements:
        if e is elements[-1]:
            json+='"%s"' % e 
            break
        json+='"%s",' % e 

上面的代码适用于列表,但不能在这里工作,因为集合不支持拼接。

【问题讨论】:

  • 为什么不让 for 循环直到 elements[:-1] 然后在它下面放上你的最后一个元素代码?
  • set() 中的最后一项或list() 中的最后一项?请注意,set() 不维护插入顺序。
  • 首先谈论“集合的最后一个元素”有意义吗?
  • @nikeros 最后,或者更确切地说,final。它在集合中的实际“位置”并不重要
  • 在这种特定情况下,您可以这样做','.join(f'"{e}"' for e in elements)

标签: python loops set


【解决方案1】:

在上面留下我的评论,你可以这样做:

s = {"A", "B", "C"}

i = iter(s)

element = next(i, None)

while element is not None:
    next_element = next(i, None)
    if next_element is None:
        # This is the last element
        print(element * 10)
    else:
        print(element)
    element = next_element

输出

B
A
CCCCCCCCCC

这只是 final 元素如何应用不同转换的示例。

【讨论】:

  • 如果s = {None}怎么办?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多