[英]How to determine if item is last item in a set
I have an arbitrary number of items in a set.我在一组中有任意数量的项目。
I want to do something different when I am on the last item of the set - is it possible to do so without having to find the length of the set and have a counter variable?当我在集合的最后一项时,我想做一些不同的事情 - 是否可以这样做而不必找到集合的长度并有一个计数器变量?
for e in elements:
if e is elements[-1]:
json+='"%s"' % e
break
json+='"%s",' % e
The above code will work for lists, but cannot work here as splices are not supported for sets.上面的代码适用于列表,但不能在这里工作,因为集合不支持拼接。
Leaving my comment above, you could do something like this:在上面留下我的评论,您可以执行以下操作:
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
OUTPUT OUTPUT
B
A
CCCCCCCCCC
This is just an example how the final element could be applied a different transformation.这只是如何将最终元素应用于不同转换的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.