【问题标题】:Is it possible to search through an entire tuple for an entry without iterating?是否可以在不迭代的情况下搜索整个元组中的条目?
【发布时间】:2020-08-12 18:09:17
【问题描述】:

我的程序需要搜索包含月份数字和值的列表。 (一月是 1,二月是 2 等等......)。 如果它找到月份整数,我想将其对应的值附加到 avg_tuple 数组中。如果它没有找到月份整数,我希望它在 output_tuple 数组中附加“N/A”以进行报告。是否可以在不使用以下内容的情况下搜索我的列表: {对于我在我的列表中:} 方法?

例如,我的程序的目的是取一月份所有值的平均值。然后举报。然后取二月和一月的平均值并报告。然后是三月、二月和一月(依此类推,随着月份的继续......)。如果一个月没有此列表的值,我希望它报告 N/A。我试过 { if x in my_list } 方法没有成功。

这是我的代码:

my_list = [(2, 181), (2, 183), (3, 376), (4, 205)]
input tuple = my_list

#Function to calculate and report back the average duration for each month
def average_duration(input_tuple):
    output_tuple = []
    average_tuple = []

    for number in range(1,13):
        for i in input_tuple:
            if i[1] == number:
                average_tuple.append(i[3])
        if len(average_tuple)==0:
            output_tuple.append("N/A")
            pass
        else:
            output_tuple.append((sum(average_tuple))/len(average_tuple))

    return output_tuple

这是我当前的输出。每个值都是针对每个月的。 (我使用 OpenPyxl 在电子表格中报告它们):

my_list     N/A 182 246.6666667 236.25  236.25  236.25  236.25  236.25  236.25  236.25  236.25  236.25

这是我的预期输出:

my_list     N/A,  182,  246.6666667, 236.25,  N/A,  N/A,  N/A,  N/A,  N/A,  N/A,  N/A,  N/A

【问题讨论】:

  • i 的索引已更改(您使用的是 1 和 3,而不是 0 和 1)。您的代码现在为我打印所有N/A

标签: python arrays for-loop tuples iteration


【解决方案1】:

您可以尝试利用字典来一次跟踪所有月份,这样您就不必多次循环:

from collections import defaultdict

my_list = [(2, 181), (2, 183), (3, 376), (4, 205)]
input_tuple = my_list

#Function to calculate and report back the average duration for each month
def average_duration(input_tuple):
    months = defaultdict(list)

    output_tuple = []

    for month, value in input_tuple:
        months[month].append(value)

    overall_report = []
    for month in range(12):
        report = months[month + 1]
        if not report:
            output_tuple.append("N/A")
        else:
            overall_report.extend(report)
            output_tuple.append(sum(overall_report)/len(overall_report))

    return output_tuple

print(average_duration(input_tuple))

结果:

['N/A', 182.0, 246.66666666666666, 236.25, 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A']

从复杂性的角度来看,这基本上与您所能获得的一样有效。您修改后显示的代码复杂度为O(12 * n),而这是O(12 + N)。一个并不比另一个效率低得多,但是如果不遍历整个数组,您就无法准确找到这些平均值,因此您只能使用O(N)

【讨论】:

  • for month in range(12): 我认为这不是迭代的范围(一月在他的代码中是 1)。应该是for month in range(1,13):
  • 是的,完全忘了加一,谢谢你的收获
  • 非常感谢!你是最好的!我已经坚持了两天了。再次感谢您的所有帮助:)
猜你喜欢
  • 2010-12-22
  • 1970-01-01
  • 2021-03-23
  • 2022-11-10
  • 2019-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多