根据条件语句对元组列表中的元组进行分类



我希望你能帮助我解决我一直在努力解决的逻辑问题。

我有一个元组列表,格式如下:

[(2, 1), (2, 2), (3, 1)]

每个元组(人(包含两个数字。第一个数字是例如苹果的数量(a(,第二个数字是香蕉的数量(b(。

我想要的是在元组列表中找到两个元组,并将它们分为两类,比如说邪恶和善良。

因此,一般规则如下:如果一个人没有香蕉,那么苹果最多的人就是好人拥有最多香蕉的人是邪恶的,如果这个人没有苹果

示例1:

[(3, 0), (2, 1), (0, 3)]

结果

索引为0的
  • 元组很好,因为它拥有最多的苹果
  • 索引为2的元组是邪恶的,因为它有最多的香蕉

如果一个人既有苹果又有香蕉,那么我想要以下几种:这个人擅长用最多的苹果和最少的香蕉。然而,如果有一个人的香蕉比苹果最多的人少,那么这个人就是好人,例如:

示例2:

[(1, 0), (2, 1)]

结果

索引为0的
  • 元组很好,因为它有一个苹果
  • 索引为1的元组是邪恶的,因为它有一个香蕉

示例3:

[(2, 1), (2, 2), (3, 1)]

结果

索引为1的
  • 元组是邪恶的,因为它有最多的香蕉
  • 索引为2的元组有好处,因为它有最多的苹果,比大多数香蕉都少

示例4:

[(2, 1), (2, 2), (2, 2)]

结果

索引为1和2的
  • 元组是邪恶的,因为它有最多的香蕉
  • 索引为0的元组有好处,因为它有最多的苹果,比大多数香蕉都少

到目前为止,我所尝试的是将元组列表拆分为两个列表,例如:

  • len_apples_per_person=(2,2,2(
  • len_bananas_per_person=(1,2,2(

但由于苹果和香蕉之间的关系决定了一个人是好是坏,我认为这不是正确的方式。

如果元组列表中的元组具有(0,0(,则应忽略。我有一个变通办法,但有点笨拙,所以如果有人能想出一个解决我问题的办法,我会很高兴的。

下面是一个代码示例。我意识到,为了效率,我应该在循环之外有最小值和最大值,它不会改变。无论如何,这个代码示例并不能涵盖所有内容。

#Here we check which person is the good and evil
for idx in range(len(len_apples_per_person)):
if len_apples_per_person[idx] == min(len_apples_per_person) and 
len_bananas_per_person[idx]!=0:
idx_evil = idx
if len_apples_per_person[idx] ==  max(len_apples_per_person):
idx_good = idx
print(idx_good, idx_evil)

我希望有人能帮我理清逻辑。

经过很长时间,我终于解决了自己的问题。

我最终研究了苹果和香蕉之间的关系,这大大简化了代码。

然而,仍然有一些例外,我需要添加更多的代码来获得正确的索引。

下面是一个工作代码示例,我在其中介绍了9个示例。

def retrieve_good_evil_idx(listoftuples=None):
"""
Retrieves the index of the good and evil in a list of tuples
"""
start_apple_to_banana = -1
start_banana_to_apple = -1
store_banana = 0
store_apple = 0
for idx, (apple, banana) in enumerate(listoftuples):
try:
apple_to_banana = apple/banana
banana_to_apple = banana/apple
except ZeroDivisionError:
apple_to_banana = apple
banana_to_apple = banana
if apple_to_banana > start_apple_to_banana:
idx_good = idx
if banana_to_apple > start_banana_to_apple and idx != 0:
idx_good = idx-1
if store_apple == 0 and idx != 0:
idx_good = idx
if banana_to_apple > start_banana_to_apple:
idx_evil = idx
if store_apple == 0 and idx != 0:
idx_evil = idx-1

start_apple_to_banana = apple_to_banana
start_banana_to_apple = banana_to_apple
store_apple = apple
store_banana = banana

return idx_good, idx_evil
apples_bananas = (
[(2, 1), (2, 2), (3, 1)], 
[(3, 0), (2, 1), (0, 3)], 
[(1, 0), (2, 1)], 
[(2, 1), (2, 2), (3, 1)], 
[(2, 1), (2, 2), (2, 2)],
[(1, 1), (1, 1)],
[(1, 2), (1, 0)],
[(0, 1), (1, 2)],
[(1, 2), (2, 1)]
)
print('(good index, evil index)')
for i in apples_bananas:
print(retrieve_good_evil_idx(listoftuples=i))
(good index, evil index)
(2, 1)
(0, 2)
(0, 1)
(2, 1)
(0, 1)
(0, 0)
(1, 0)
(1, 0)
(1, 0)

我知道代码是次优的,所以如果你能帮助我优化代码并提出反馈,我会非常高兴。

最新更新