如何在python中检查元素是否只在列表中出现一次?
我有一个列表:
a = [1, 2, 6, 4, 3, 5, 7]
请向我解释如何检查元素是否在列表中只出现一次?
请同时解释一下从 1 到 len(a) 的所有元素是否都在列表中。例如,在列表“a”中,从 1 到 7 的元素都在列表中,但如果列表是 b = [1, 4, 3, 5]
,则并非所有从 1 到 4 的元素不在列表中。
谢谢你!
I have a list:
a = [1, 2, 6, 4, 3, 5, 7]
Please, explain to me how to check whether element appears only once in in the list?
Please, also explain if all elements from 1 to len(a)
are in the list. For instance, in list 'a' element from 1 to 7 are in the list, but if the list is b = [1, 4, 3, 5]
, then not all elements from 1 to 4 are not in the list.
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当我读到你的问题时,我从中得到了与马克不同的含义。如果您想检查特定元素是否只出现一次,则
仅当
item
在列表中只出现一次时才为 true。第二个问题见 Pokes 的回答
When I read your question, I took a different meaning from it than mark did. If you want to check if a particular element appears only once, then
will be true only if
item
occurs in the list exactly once.See Pokes answer for the second question
对于第一个问题,
对于第二个问题。
for the first question, and
for the second.
对于你的第一个问题,如果你的元素是可散列的,你可以创建一个包含元素的集合并检查其长度:
或者你可以使用这个函数,如果结果为 False,它可以提供比上面更好的性能(但当结果为 True 时性能更差) ):
For your first question if your elements are hashable you can create a set containing the elements and check its length:
Alternatively you can use this function which can give better performance than the above if the result is False (but worse performance when the result is True):
对于第二个问题,您可能需要检查
For the second question you might want to check
我知道你想要这样的东西:
i understood you want something like that: