简体   繁体   English

如果为空,则在子列表中输入值

[英]Entering value in sublist if empty

So I have a larger for loop which produces nested lists of various of sizes: eg 所以我有一个更大的for循环,它会产生各种大小的嵌套列表:例如

[[6], [3], [5], [3, 2, 5, 3], [5], [6, 5, 4], [5, 3, 2]]
[[5], [], [], [4], [3]]
[[5], [2]]
[[], [4], [3, 2, 4]

In short, I would like it so that each array that has an empty sublist to simply be the value 0. So like : If the list generated is : [[6], [3], [5], [3, 2, 5, 3], [5], [6, 5, 4], [5, 3, 2]] 简而言之,我希望每个具有空子列表的数组都简单地成为值0。就像:如果生成的列表是: [[6], [3], [5], [3, 2, 5, 3], [5], [6, 5, 4], [5, 3, 2]]

Then I would keep it that way. 然后我会保持这种方式。

But if the list generated is: [[5], [], [], [4], [3]] 但是,如果生成的列表是: [[5], [], [], [4], [3]]

Then I would like it to be: [[5], [0], [0], [4], [3]] 然后,我希望它是: [[5], [0], [0], [4], [3]]

Likewise, for the final row above, I would want it to be: [[0], [4], [3, 2, 4] 同样,对于上面的最后一行,我希望它是: [[0], [4], [3, 2, 4]

I have been trying something along the lines of : 我一直在尝试以下方法:

for k in range(0,len(TempAisle)):
           if TempAisle[k][0] == None:
               TempAisle[k][0]= 0
 k+=1

But I am getting an list index out of range error. 但是我得到list index out of range错误。

It seems to be a rather simple problem and have seen others who have asked ways to check if there is a sublist that is empty but I am having trouble replacing it with another value (0 in my case). 这似乎是一个非常简单的问题,并且看到其他人询问如何检查子列表是否为空,但是我很难用另一个值(在我的情况下为0)替换它。 Any help and explanation will be appreciated. 任何帮助和解释将不胜感激。

You can iterate on the items directly - the more Pythonic way - no need to use range . 您可以直接迭代这些项目(更Python化的方式),而无需使用range Test for the truthiness of each of the items (empty lists are falsy ), and append a zero only if the sublist is empty: 测试每个项目的真实性(空列表为falsy ),并且仅在子列表为空时追加零:

for x in TempAisle:
    if not x:
        x.append(0)

For a one-line solution: 对于单线解决方案:

x = [elem or [0] for elem in TempAisle]

An EDIT based on the comment of @Moses Koledoye, to avoid creating a new list, but to keep it as a one-line solution: 基于@Moses Koledoye的注释的EDIT,以避免创建新列表,但将其保留为单行解决方案:

[x.append(0) for x in TempAisle if not x]

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

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