itertools/groupby/for循环

mepcadol  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(342)

我最近一直在寻找一种更好的方法来检查 group 是否已处理。所需的代码行如下所示( if (key == group[0][0]): ). 我试图实现的想法如下:
必须在循环的每一轮中对其进行检查 for group in groups ,如果满足上述条件。因此,在第一组中的所有项目都已打印之后,for循环将跳转到下一组并执行相同的操作(在检查第二个条件之后) if (key == item[0]): ). 因此,要点是防止for循环跳转到下一组,因为每个项的键和第一个元素之间不匹配,这意味着;在那里找不到或打印任何元素。话虽如此,我还是尽量避免跳入其他有另一把钥匙的小组,这样可以节省时间和内存。
所以问题是,;如果有更好的方法来实现这个想法,因为我自己的措辞条件有点原始(检查第一个单词是否与关键单词相同)。
非常感谢!

things = [("animal", "lion"), ("object", "computer"), ("animal", "giraffe"), ("animal","tiger"),("object","table"),("clothes", "jacket"), ("animal", "dog")]
sorted_things = sorted(things)
groups = []
special_keys = []
for key, group in groupby(sorted_things, lambda x: x[0]):
    groups.append(list(group))
    special_keys.append(key)
counting = 0
for key in special_keys:
    print("These things are to this key " + key + " sorted: ")
    for group in groups:
        if (key == group[0][0]):
            for item in group:
                if (key == item[0]):
                    print("                                          ",item[1])

以下是输出:

These things are to this key animal sorted:
                                           dog
                                           giraffe
                                           lion
                                           tiger
These things are to this key clothes sorted:
                                           jacket
These things are to this key object sorted:
                                           computer
                                           table
i7uaboj4

i7uaboj41#

所以问题是,;如果有更好的方法来实现这个想法
以下是我将如何获得相同的输出:

from itertools import groupby
from operator import itemgetter

sorted_things = [
 ('animal', 'dog'),
 ('animal', 'giraffe'),
 ('animal', 'lion'),
 ('animal', 'tiger'),
 ('clothes', 'jacket'),
 ('object', 'computer'),
 ('object', 'table'),
]

for key, values in groupby(sorted_things, key=itemgetter(0)):
    print(f'These things are to this key {key} sorted:')
    for key, value in values:
        print(' ' * 42, value)

请注意,groupby()函数已经具有这样的逻辑:“在第一个组中的所有项目都已打印完毕后,for循环将跳转到下一个组。”
无需检查第一个元素以匹配键。groupby()函数已经为您完成了这项工作。

相关问题