【问题标题】:slice a dictionary on elements contained within item arrays对包含在项目数组中的元素切片字典
【发布时间】:2015-05-08 00:59:18
【问题描述】:

假设我有一个国家/地区的字典 -> [城市](可能是一个有序的字典):

{'UK': ['Bristol', 'Manchester' 'London', 'Glasgow'],
 'France': ['Paris', 'Calais', 'Nice', 'Cannes'],
 'Germany': ['Munich', 'Berlin', 'Cologne']
} 

键(国家)的数量是可变的:数组中的元素城市的数量也是可变的。结果集来自对城市名称的“搜索”,因此,例如,对“San%”的搜索可能会遇到 50k 个结果(在全球搜索中)

数据将用于填充 select2 小部件 --- 我想使用它的分页功能......

有没有一种聪明的方法来切片这个[3:8] 会产生:

{'UK': ['Glasgow'],
 'France': ['Paris', 'Calais', 'Nice', 'Cannes'],
 'Germany': ['Munich']
} 

(对于之前提出这个问题的方式表示歉意——我不确定真正的用法会澄清这个问题......)

【问题讨论】:

  • 字典中是否总是只有这 3 个 a b 和 c 条目?永不止步?
  • 这背后的逻辑是什么?为什么 [3:8] 会产生这样的结果?
  • 通过连接“子”数组/列表,您将得到 [1,2,3,4,5,6,7,8....]。我试图保留“结构”,同时从中取出块(基本上是限制/偏移)。
  • 基本上你想将所有列表合并到一个大列表中,对该列表进行切片,然后以某种方式将结果重新分配回字典中的原始键?
  • 我仍然不清楚规则是什么。也许如果您发布了非智能版本,它可能很笨重但可以满足您的需求,我们可以想办法改进它?

标签: python-2.7 dictionary slice


【解决方案1】:

如果我正确理解您的问题,正如 cmets 中所述,应该这样做

from pprint import pprint

def slice_dict(d,a, b):
  big_list = []
  ret_dict = {}
  # Make one big list of all numbers, tagging each number with the key
  # of the dict they came from.
  for k, v in d.iteritems():
    for n in v:
      big_list.append({k:n})
  # Slice it
  sliced = big_list[a:b]

  # Put everything back in order
  for k, v in d.iteritems():
    for subd in sliced:
      for subk, subv in subd.iteritems():
        if k == subk:
          if k in ret_dict:
            ret_dict[k].append(subv)
          else:
            ret_dict[k] = [subv]

  return ret_dict

d = {
  'a': [1, 2, 3, 4],
  'b': [5, 6, 7, 8, 9],
  'c': [10, 11, 12, 13, 14]
}

x = slice_dict(d, 3, 11)
pprint(x)

$ python slice.py 
{'a': [4], 'b': [5, 6], 'c': [10, 11, 12, 13, 14]}

输出与您的示例输出略有不同,但这是因为 dict 在传递给函数时没有排序。是a-c-b,这就是为什么b在6处被切断而c没有被切断

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多