我有一个可变长度元组的列表。如何将其转换为字典?
class StringArrayList {
// make the variable private, to protect it from being modified from outside the class
private final String[] arr;
StringArrayList(int size) {
// constructors are the only method allowed to set final variables
arr = new String[size];
}
String get(int i) {
// get method doesn't change the state of the object, so is fine
// However, if the object returned is mutable then there might be issues.
return arr[i];
}
void set(int i, String item) {
// set changes the state of arr, and so with this method, StringArrayList cannot
// be considered immutable
arr[i] = item;
}
}
使用理解功能时出现错误
tup = [ ("x", 1), ("x", 2, 4), ("x", 3), ("y", 1), ("y", 2), ("z", 1), ("z", 2, 3) ]
错误:
{key: [i[1:] for i in tup if i[0] == key] for (key, value) in tup}
预期输出:
ValueError
Traceback (most recent call last)
>ipython-input-26-bedcc2e8a704< in module()
----> 1 {key: [i[1] for i in tuplex if i[0] == key] for (key, value) in tuplex}
>ipython-input-26-bedcc2e8a704< in dictcomp((key, value))
----> 1 {key: [i[1] for i in tuplex if i[0] == key] for (key, value) in tuplex}
ValueError: too many values to unpack
答案 0 :(得分:7)
这似乎不是列表理解的任务。您可以使用字典的setdefault
方法通过简单的for
循环将密钥的默认值设置为一个空列表,然后使用该元组中的值extend
将该列表设置为:
tup = [ ("x", 1), ("x", 2, 4), ("x", 3), ("y", 1), ("y", 2), ("z", 1), ("z", 2, 3) ]
res = {}
for k, *rest in tup:
res.setdefault(k, []).extend(rest)
print(res)
# {'y': [1, 2], 'x': [1, 2, 4, 3], 'z': [1, 2, 3]}
对于Python 2.7,我认为您无法像这样打开一个元组,因此您可以尝试执行以下操作:
for t in tup:
res.setdefault(t[0], []).extend(t[1:])
答案 1 :(得分:0)
tup = [("x", 1), ("x", 2, 4), ("x", 3), ("y", 1), ("y", 2), ("z", 1), ("z", 2, 3)]
data = {}
for item in tup:
if item[0] in data:
data[item[0]] = data[item[0]] + list(item[1:])
else:
data[item[0]] = list(item[1:])
print(data)