Python 如何将子列表添加到子列表?

Python 如何将子列表添加到子列表?,python,python-2.7,list,comparison,sublist,Python,Python 2.7,List,Comparison,Sublist,在某些情况下,我想将一个子列表附加到前一个子列表,即如果其长度小于2。因此,[5]的长度小于2,现在前面的列表将扩展为5(a+b) a=[1,1,1,1] b=[5] c=[1,1,1] d=[1,1,1,1,1] e=[1,2] f=[1,1,1,1,1,1] L=[a,b,c,d,e,f] 打印“列表:”,L def short(列表): 结果=[] 对于列表中的值: 如果len(value)这可能会有所帮助 Ex: a = [1,1,1,1] b = [5] c = [1,1,1] d =

在某些情况下,我想将一个子列表附加到前一个子列表,即如果其长度小于2。因此,
[5]
的长度小于2,现在前面的列表将扩展为5(a+b)

a=[1,1,1,1]
b=[5]
c=[1,1,1]
d=[1,1,1,1,1]
e=[1,2]
f=[1,1,1,1,1,1]
L=[a,b,c,d,e,f]
打印“列表:”,L
def short(列表):
结果=[]
对于列表中的值:
如果len(value)这可能会有所帮助

Ex:

a = [1,1,1,1]
b = [5]
c = [1,1,1]
d = [1,1,1,1,1]
e = [1,2]
f = [1,1,1,1,1,1]

L = [a,b,c,d,e,f]

print( 'List:', L)

def short(lists):
    result = []
    for value in lists:
        if len(value) <= 2:            #check len
            result[-1].extend(value)   #extend to previous list
        else:
            result.append(value)       #append list. 
    return result

result = short(L)
print( 'Result:', result)
List: [[1, 1, 1, 1], [5], [1, 1, 1], [1, 1, 1, 1, 1], [1, 2], [1, 1, 1, 1, 1, 1]]
Result: [[1, 1, 1, 1, 5], [1, 1, 1], [1, 1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 1, 1]]

将您的功能更改为:

def short(lists):
result = []
for value in lists:
    if len(value) < 2 and result:
        result[-1].extend(value)
    else:
        result.append(value)
return result
def short(列表):
结果=[]
对于列表中的值:
如果len(值)<2,结果:
结果[-1]。扩展(值)
其他:
result.append(值)
返回结果

在您的情况下,您有
和结果
。您的
结果
列表开始为空,因此此条件开始为false,并且它阻止任何添加到
结果
,因此该条件将永远不会通过。如果第一个列表太短,它将失败,除非您添加
和结果
条件谢谢!我看到了你的评论并改变了它!