简体   繁体   English

python-将项目追加到列表中始终作为子列表

[英]python - append item to list always as a sub-list

What would be the most efficient way to append an item into an existing list as another sub-list. 将项目作为另一个子列表追加到现有列表中的最有效方法是什么。 for instance, considering data['rows'] is a list, the following: 例如,考虑到data ['rows']是一个列表,如下所示:

 for indx, row in enumerate(my_data):
    data['rows'].append(row) 

does the job in when row is already a list. 当行已经是列表时,执行作业。

> 'Rows': [['150', '01'], ['10', '02'], ['22', '03'], ['33', '4'] ...

however if the value in row is not a list, this will produce: 但是,如果row中的值不是列表,则将产生:

> 'Rows': ['150', '10', '22', '33', '44', '15']

I've a condition that in case a row is not a list it uses data['Rows'].append(list(row)) but there must be a better way.. 我有一个条件,如果行不是列表,它会使用data['Rows'].append(list(row))但必须有更好的方法。

If I understand your question, something like 如果我了解您的问题,类似

I have a list of elements, these elements may be lists already, they may not be. 我有一个元素列表,这些元素可能已经是列表,但可能不是。 If they are lists, I want them appended as such. 如果它们是列表,我希望将它们原样添加。 If they aren't lists, I want them wrapped in a list, and then I want the resulting single-element list appended. 如果它们不是列表,我希望将它们包装在一个列表中,然后再将生成的单元素列表追加。

This is something I too have struggled with, and the best I could come up with is something like the following: 这也是我一直在努力的事情,而我能想到的最好的东西如下:

elems = [1,2,[3,4],5]

data1 = []
for e in elems:
    data1.append(e if isinstance(e, list) else [e,])
print data1

# Or with a lambda function that does the work for you
wrap = lambda x: x if isinstance(x, list) else [x,]

data2 = []
for e in elems:
    data2.append(wrap(e))
print data2

Both output: 两种输出:

[[1], [2], [3, 4], [5]]

If I understood your question correctly, you could do something like this: 如果我正确理解了您的问题,则可以执行以下操作:

data['Rows']=data.get('Rows', []).append(list(row))

This will create the list if it isn't present in the dictionary already. 如果列表不在词典中,则将创建该列表。

You might consider rephrasing your question to make it more clear. 您可以考虑改写您的问题以使其更清楚。 You say "if it's not a list", but it isn't clear what it is then. 您说“如果不是列表”,但是不清楚它是什么。 Since you are working with dicts I assumed it meant that the key is not present. 由于您正在使用字典,因此我认为这意味着该密钥不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM