如何从for循环中获取多个值?
我有一个列中的记录列表,该列表被命名为日期。我正在尝试从列表中获取不同的日期。该列表有许多重复的日期,例如 1/1/2010、1/1/2010,...。但也有不同的日期。 但如果我使用:
for date in dates: ....
它会为每个日期重复循环(无论是否相同),而不是不同的日期。我怎么能告诉它这样做:
for differentdate in dates:...
语言是Python!!
I have a list of records from a column, the list is named as dates. I am trying to get different dates out of the list. The list have many repetitive dates, such as 1/1/2010,1/1/2010, …. but there are different dates too.
But if i use:
for date in dates: ....
it's repeating the loop for every single date(no matter if it is the same or not), not different dates. How could I tell it to do:
for differentdate in dates:...
The language is Python!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
set()
用另一个集合中的唯一元素创建一个集合。注意:这可能不会保留原始列表的顺序,因此如果您需要保留该顺序,请遵循 @GregHewgill 的答案。set()
makes a collection out of the unique elements in another collection. Note: this may not preserve the order of the original list, so if you require that order to be preserved, go with @GregHewgill's answer.您可以使用 itertools 模块按日期进行分组。例如:
这保留了
a
中元素的原始顺序(这对您来说可能很重要)。在循环内部,g
是一个生成器,它生成一个包含具有该键的每个元素的序列。请参阅itertools.groupby
的文档更多信息。You can use the itertools module to group by the dates. For example:
This preserves the original order of the elements in
a
(which could be important for you). Inside the loop,g
is a generator that produces a sequence containing each element with that key. See the documentation foritertools.groupby
for more information.以下任一:
可用作
Either of the following:
can be used as
如果保留顺序很重要,则以下生成器函数源自 Alex Martelli 关于 从序列中删除重复项 ActiveState 配方可以工作(并且基于这些 bench-marks 其中包括原始的基于字典的非生成器 Martelli 示例):
另一个不错的功能是它相当灵活,可以通过提供自定义
idfun
用于检索要比较的数据。If preserving order was important, the following generator function derived from a comment by Alex Martelli about the Remove duplicates from a sequence ActiveState recipe would work (and should also be relatively fast based to these bench-marks which included the original dictionary-based, non-generator Martelli exemplar):
Another nice feature is that it's fairly flexible and can be adapted to other data structures by providing a custom
idfun
to use to retrieve the datum to be compared.