Skip to main content
 首页 » 编程设计

python之组合字典列表元素是长度大于 2

2024年09月07日8zhwl

我有一本包含值列表的字典。列表的长度不能大于 2。我需要做的是从第二个元素开始组合列表元素并与下一个元素连接,直到列表的长度等于 2。我在下面的尝试有效,但它这似乎可以更容易地完成,但我只是没有看到。

testDict = {'60075566': ['A', u'foo'],  
            '60074783': ['B', u'one', u'two', u'three', u'four', u'five'],  
            '60069249': ['C', u'test1', u'test2', u'test3'],  
            '60075936': ['D', u'bar'], '60073582': []} 
 
 
for key in testDict: 
    while len(testDict[key]) > 2: 
        dataSave = testDict[key][0]         #####save first element of the dictionary value####### 
        newList = testDict[key]             #####create new list of values to change####### 
        newList.pop(0)                      #####pop the first element, previosuly saved##### 
        newData = ','.join(newList )        #####Join remaining elements##### 
        testDict[key] = [dataSave, newData] #####Replace old value with new value 

上面给出了答案,但我觉得它可以改进:

{'60069249': ['C', u'test1,test2,test3'], '60075566': ['A', u'foo'], '60075936': ['D', u'bar'], '60074783': ['B', u'one,two,three,four,five'], '60073582': []} 

请您参考如下方法:

解决这些问题的最佳方法是使用推导式(这里是字典推导式)重建一个以值长度为条件的新字典:

testDict = {'60075566': ['A', u'foo'], 
            '60074783': ['B', u'one', u'two', u'three', u'four', u'five'], 
            '60069249': ['C', u'test1', u'test2', u'test3'], 
            '60075936': ['D', u'bar'], '60073582': []} 
 
result = {k:(v if len(v)<=2 else [v[0],",".join(v[1:])]) for k,v in testDict.items()} 
 
print(result) 

打印:

{'60075936': ['D', 'bar'], '60073582': [], '60075566': ['A', 'foo'],  
 '60074783': ['B', 'one,two,three,four,five'], '60069249': ['C', 'test1,test2,test3']} 

在v if len(v)<=2 else [v[0],",".join(v[1:])] ,如果长度为 2 或更小,则列表/值保持不变,否则它将从第一个元素和其余元素的连接字符串重建。