解析csv文件后,我从以下行之一获取此列表:
['', 'value1', '346.897', '', 'value2', '202.306', 'value3', '136.880', 'value4', '7.711', '']
因此,我需要获得:
{
'value1': 346.897,
'value2': 202.306,
...
}
有人知道如何使其美丽吗?不使用索引。
现在,我从列表中删除所有空字符串,然后使用[0]
之类的key
和[1]
之类的value
等。
Variables :value1 # ... - are dynamic
答案 0 :(得分:5)
s = ['', 'value1', '346.897', '', 'value2', '202.306', 'value3', '136.880', 'value4', '7.711', '']
s = list(filter(None, s)) # fastest way to remove the empty strs
zipped = zip(s[0::2], s[1::2]) # zip them
print({k:v for k,v in dict(zipped).items()})
输出:
{'value1': '346.897', 'value2': '202.306', 'value3': '136.880', 'value4': '7.711'}
缩略语版:
s = list(filter(None, s))
print(dict(zip(s[0::2], s[1::2])))
输出:
{'value1': '346.897', 'value2': '202.306', 'value3': '136.880', 'value4': '7.711'}
答案 1 :(得分:2)
您可以从列表中删除空元素,将元素分成2个大块,然后使用dict理解。
例如:
data = ['', 'value1', '346.897', '', 'value2', '202.306', 'value3', '136.880', 'value4', '7.711', '']
data = [i for i in data if i] #Clean data
data = [data[i:i+2] for i in range(0, len(data), 2)] #Divide list elements to chunks of 2
result = {k: v for k, v in data} #dict comprehension
print(result)
输出:
{'value1': '346.897',
'value2': '202.306',
'value3': '136.880',
'value4': '7.711'}
答案 2 :(得分:2)
一种实现方法是首先摆脱空字符串,然后将其转换为字典,知道您需要对索引采取2步以从一对(键,值)到下一个:
L = ['', 'value1', '346.897', '', 'value2', '202.306', 'value3', '136.880', 'value4', '7.711', '']
L = [elt for elt in L if elt != '']
D = {L[k]:L[k+1] for k in range(0, len(L), 2)}
输出:
Out[8]:
{'value1': '346.897',
'value2': '202.306',
'value3': '136.880',
'value4': '7.711'}
答案 3 :(得分:1)
您可以尝试以下操作:
input_list = ['', 'value1', '346.897', '', 'value2', '202.306', 'value3', '136.880', 'value4', '7.711', '']
# Filtering for empty strings
res = [item for item in input_list if item != ""]
# Making pairs of list items
pairs = zip(res[::2], res[1::2])
res_dict = dict(pairs)
print (res_dict)
输出:
{'value1': '346.897', 'value2': '202.306', 'value3': '136.880', 'value4': '7.711'}
答案 4 :(得分:1)
如果您确定列表中的相邻key
和value
对。您可以仅通过该iterator
制作一个list
并像这样制作一个dict
,
>>> data
['', 'value1', '346.897', '', 'value2', '202.306', 'value3', '136.880', 'value4', '7.711', '']
>>> data_ = [x for x in data if x] # clean the data
>>> d = iter(data_) # make an iterator
>>> {x: next(d) for x in d}
{'value4': '7.711', 'value3': '136.880', 'value2': '202.306', 'value1': '346.897'}