list - python: 匹配列表中的元素

144 3
时间:

84 3

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'}



pyFiddle

原作者:
65 0

您可以从列表中删除空元素,将元素划分为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'}



原作者:
60 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'}



原作者:
142 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'}



原作者:
150 2

如果你确定相邻的key,则列表中的value 对。 你可以从该列表中创建一个迭代器,然后从中创建一个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'}



...