【问题标题】:Python: append a list from a dictionary with conditionsPython:从带有条件的字典中附加一个列表
【发布时间】:2020-10-01 16:48:24
【问题描述】:

我有一本字典,我想从中过滤出来并将结果附加到另一个字典中。条件是如果字典中两个第一个元素(例如 31 - 30 = 1)之间的差异小于 5,则添加字典的相关第二个元素并将其附加到新字典中,否则保持相同的第一个元素与关联的第二个元素。

a = {"20" : "1.5", "30" : "2.0", "31" : "1.0", "40" : "1", "50" : "1.5"}
listb = []
listc = []
newdict = {}
for key in a:
    b = key
    c = a[key]
    listb.append(b)
    listc.append(c)

for i in range(len(listb)):
    low = listb[i]
    high = listb[i+1]
    diff = int(high) - int(low)
#     print(low)
    if (diff > 5):
        num = listc[i]
#         print(num)
        num_a = listb[i]
#         print(num_a)
        newdict[[num_a][i]] = num
        print((newdict))
    else:
        num = listc[i] + listc[i+1]
        print(num)
        num_a = listb[i+1]
        print(num_a)
        newdict[[num_a][i]] = num
print(newdict)

这个输出应该看起来像

a = {“20”:“1.5”,“31”:“3.0”,“40”:“1”,“50”:“1.5”}

【问题讨论】:

    标签: python pandas dictionary append


    【解决方案1】:

    一种方法是先将其转换为Pandas dataframe,然后在那里进行计算,然后再将其转换回字典?

    d = {"20" : "1.5", "30" : "2.0", "31" : "1.0", "40" : "1", "50" : "1.5"}
    df = pd.Series(d)
    df = df.reset_index().astype(float)
    df['id']= df['index'].diff().shift(-1).fillna(10).values
    df = df[df['id']>5]
    df = df.set_index(['index'])
    df = df.drop('id', axis=1)
    df.to_dict()
    {0: {20.0: 1.5, 31.0: 1.0, 40.0: 1.0, 50.0: 1.5}}
    

    【讨论】:

    • 感谢 XXavier 花时间研究这个问题。这是一个很好的方法!只是在输出中它应该是 {20.0: 1.5, 31.0: 3.0, 40.0: 1.0, 50.0: 1.5} 但可以进行这些更改。
    【解决方案2】:

    由于您要将每个元素与“之前”或“之后”的元素进行比较,因此您希望使用有序的数据结构。由于字典只是“插入排序”,因此您无法可靠地检查第一个项目和紧随其后的项目。因此,您可能想要使用元组列表。我不太确定您要做什么,但我试图用这段代码来解释它。我希望这会有所帮助:)

    # Creating a as a list of tuples so that they are ordered
    a = [(20, 1.5), (30, 2.0), (31, 1.0), (40, 1), (50, 1.5)]
    new_list = []
    
    # you looped through len(a), but you should loop through len(a) - 1 so that you don't get an index error
    for i in range(len(a) - 1):
        # The first element of each tuple
        low_key = a[i][0]
        high_key = a[i+1][0]
    
        if high_key - low_key < 5:
            sum = a[i+1][1] + a[i][1]
            new_tuple = (high_key, sum)
            new_list.append(new_tuple)
        else:
            new_list.append((low_key, a[i][1]))
            # need to check if last element, bc only looping through len(a) - 1
            if i == len(a) - 1:
                new_list.append((high_key, a[i+1][1]))
    print(new_list)
    

    【讨论】:

    • Sam,非常感谢您关注这个问题。您的解决方案非常适合我的情况!再次感谢!
    • 字典是从我认为 3.6 开始订购的
    • 这个方案比pandas好
    【解决方案3】:

    我不太清楚您要做什么,但我认为使用几个 cmets,您可能能够修复您的代码以实现您的目标,即使我不完全理解那是什么目标是。

    dict 本质上是未排序的,但我相信您的算法本质上要求键按升序排列。

    我将第二行和第三行改为:

    listb = sorted(a.keys())
    listc = [a[k] for k in listb]
    

    接下来您可能想要循环到 len(listb) - 1。否则 listb[I + 1] 将超出范围。也许您可以查看 enumerate 函数,但随后您需要检查是否处于最后一次迭代中,并进行相应处理。

    最后,您可以使用一些更好的变量名。 a、listb 和 listc 并没有真正传达太多含义。即使是 a、a_keys 和 a_values 也会更容易理解,但更好地描述 a 代表的内容会更好。

    【讨论】:

      【解决方案4】:

      如果唯一的其他答案需要使用 Pandas,那么我觉得有必要提供一个替代方案(我讨厌 Pandas)。

      这应该给出你所描述的。不过我目前无法测试。

      a = {"20" : "1.5", "30" : "2.0", "31" : "1.0", "40" : "1", "50" : "1.5"}
      # your listb and listc are just a.keys() and a.values(). So I'm going to delete all of this listb listc setup stuff.
      newdict = {}
      
      skip = False  # This is a pretty brute force way to just check whether we've already accounted for the "next" value. Otherwise you will double count.
      
      for i in range(len(a.keys())):
          if skip:
              skip = False
              continue
          low = a.keys()[i]
          high = a.keys()[i+1]
          diff = abs(int(high) - int(low)) # If "diff" is actually meant to be a diff, then we need to use abs
          if diff > 5:
              newdict[a.keys()[i]] = a.values()[i]
          else:
              newdict[a.keys()[i]] = a.values()[i] + a.values()[i+1]
              skip = True
      print(newdict)
      

      请注意,如果您在一行中有多个键,它们的距离都

      【讨论】:

        猜你喜欢
        • 2021-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        • 2015-02-08
        • 1970-01-01
        相关资源
        最近更新 更多