【问题标题】:Trying to filter a nested tuple尝试过滤嵌套元组
【发布时间】:2021-01-06 10:54:11
【问题描述】:

我正在尝试将一个元组列表排序到一个列表中,该列表仅包含具有相同数量的偶数和奇数整数且不按顺序排列的元组。这是到目前为止的代码(如果我刚开始学习python,如果它很乱,请见谅)

from itertools import combinations as comb
import itertools
from typing import Any, Tuple, Union

# combinations

list_1 = [1,2,3,4,5,6,7,8,9,10,
          11,12,13,14,15,16,17,18,19,20,
          21,22,23,24,25,26,27,28,29,30,
          31,32,33,34,35,36,37,38,39,40,
          50,51,52,53,54,55,56,57,58,59,
          60,61,62,63,64,65,66,67,68,69]

list_2 = [1,2,3,4,5,6,7,8,9,10,
          11,12,13,14,15,16,17,18,19,20,
          21,22,23,24,25,26]


pick_5 = list(comb(list_1,5))

pick_1 = list(comb(list_2,1))

combos = list(itertools.product(pick_5,pick_1))

print("Number of unsorted combos:", len(combos))

#testing tuples

print("run test:")

print(combos[0])
print(combos[1])

print(combos[0][0][0])
print(combos[0][0][1])
print(combos[0][0][2])
print(combos[0][0][3])
print(combos[0][0][4])
print(combos[0][1][0])

#filters

combos =[]

even_odd =[
    {(t[0][0][0], t[0][0][1], t[0][0][2], t[0][0][3], t[0][0][4]), (t[0][1][0])}
    for t in combos
    if (t[0][0][0] % 2 == 0 and t[0][0][1] % 2 == 0 and t[0][0][2] % 2 == 0 and t[0][0][3] % 2 != 0 and t[0][0][4] % 2 != 0) and (t[0][1][0] % 2 != 0)
]

sequence = [
    {(t[0][0][0], t[0][0][1], t[0][0][2], t[0][0][3], t[0][0][4]), (t[0][1][0])}
    for t in combos
    if (t[0][0][0] and t[0][0][1] == t[0][0][0] + 1 and t[0][0][2] == t[0][0][0] + 2 and t[0][0][3] == t[0][0][0] + 3 and t[0][0][4] == t[0][0][0] + 4)  and (t[0][1][0] == t[0][0][0] + 5)
]

evenodd_dict = {e[0] ** 2 + e[1] ** 2 + e[2] ** 2 + e[3] ** 2 + e[4] ** 2 + e[5] ** 2 : e for e in even_odd}

sequence_dict = {s[0] ** 2 + s[1] ** 2 + s[2] ** 2 + s[3] ** 2 + s[4] ** 2 + s[5] ** 2 : s for s in sequence}

#final sort

final_dict = {}
final_dict.update(evenodd_dict)

print(final_dict)
print("done")
print ("Number of combos =", len(final_dict))

这是我得到的输出:

    Number of unsorted combos: 141999312
run test:
((1, 2, 3, 4, 5), (1,))
((1, 2, 3, 4, 5), (2,))
1
2
3
4
5
1
{}
done
Number of combos = 0

需要帮助弄清楚为什么它没有返回任何结果,我认为它在过滤器定义中

感谢您的帮助!

【问题讨论】:

  • 一个错误是在even_oddsequence 中你想用一个元素创建元组。这只是一个 int:(1),这是一个只有一个元素的元组:(1,)

标签: python list dictionary filter tuples


【解决方案1】:

在创建 even_odd 列表之前,您将 combos 重新定义为空列表。

combos =[]

even_odd =[
    {(t[0][0][0], t[0][0][1], t[0][0][2], t[0][0][3], t[0][0][4]), (t[0][1][0])}
    for t in combos
    if (t[0][0][0] % 2 == 0 and t[0][0][1] % 2 == 0 and t[0][0][2] % 2 == 0 and t[0][0][3] % 2 != 0 and t[0][0][4] % 2 != 0) and (t[0][1][0] % 2 != 0)
]

这意味着for t in combos 将循环零次,因此even_odd 也将为空。

【讨论】:

  • 啊,好吧,这对我来说很愚蠢,哈哈。删除该行会给我一个“int”不可下标错误。想法?
猜你喜欢
  • 1970-01-01
  • 2018-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-18
  • 2017-05-30
  • 2016-11-25
相关资源
最近更新 更多