我最近一直在尝试找到一种更好的方法来检查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发布于 2021-07-10 10:56:16
,所以问题是,如果有更好的方法来实现这个想法
下面是我要做的,以获得相同的输出:
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()函数已经为您完成了这项工作。
https://stackoverflow.com/questions/68324285
复制相似问题