从字典键和值中获取元组列表

时间:2015-12-10 16:34:01

标签: python loops dictionary

假设您有一份列表字典:

>>> pairs = []
>>> for k,v in a.items():
...   for id in v:
...     pairs += [(k,id)]
... 
>>> print(pairs)
[('a', 1), ('a', 3), ('a', 10), ('a', 2), ('a', 5), ('b', 1), ('b', 0), ('b', 0), ('b', 1), ('b', 14)]

从这本词典中,我想创建另一个列表,其中每个元素都是一个(key,id)元组,如下所示:

ds.list <- list(

ds.1 = as.data.frame(matrix(c(1, 0.15, 0.15, 0.15,
                              0.2, 1, 0.15, 0.15,
                              0.2, .15, 1, 0.15,
                              0.2, 0.15, 0.15, 1), nrow=4, ncol=4)),
ds.2 = as.data.frame(matrix(c(1, 0.25, 0.25, 0.25,
                              0.2, 1, 0.25, 0.25,
                              0.2, .25, 1, 0.25,
                              0.2, 0.25, 0.25, 1), nrow=4, ncol=4)),
ds.3 = as.data.frame(matrix(c(1, 0.50, 0.50, 0.50,
                              0.2, 1, 0.50, 0.50,
                              0.2, .50, 1, 0.50,
                              0.2, 0.50, 0.50, 1), nrow=4, ncol=4))
)

ds.vector <- c("ds.1", "ds.2", "ds.3") 


for (i in seq_along(ds.vector)) {
  ds <- ds.list[ds.vector[i]] #copy each of the data sets into ds
  #There would be a bunch of code here. For this example, 
  # I will just try to print
  print(ds)
}

有快捷方式吗?以前创建对的代码太冗长了。

2 个答案:

答案 0 :(得分:3)

你可以使用双列表理解 但是,易读性:

pairs = [(k, val) for k, l in a.items() for val in l]

答案 1 :(得分:0)

这也可以这样做:

>>> a = {"a":[1, 3, 10, 2, 5], "b":[1, 0, 0, 1, 14]}
>>> 
>>> [(k,v) for k in a for v in a[k]]
[('a', 1), ('a', 3), ('a', 10), ('a', 2), ('a', 5), ('b', 1), ('b', 0), ('b', 0), ('b', 1), ('b', 14)]
>>>