如何在Python的列表中插入空值?

huangapple go评论69阅读模式
英文:

How can I insert EMPTY values in python's list?

问题

我想要更改包含空值的列表,例如 [1,2,3, ,5]

我找到的所有方法都是添加 Nonenp.nan 或者只是 ''

但在我的情况下,所有这些值都不起作用,因为我只需要保留该位置为空。我该如何创建它?我需要这样做的原因是将这些值放入 scipy 的插值函数中。

英文:

Here, I have the list test_list=[1,2,3,0,5].

I want to change the list which contains empty values, like [1,2,3, ,5]

All the way I found is to add None or np.nan or just ''.

But all those values are not working at my case, cause I just need to leave the place empty. how can I create it? The reason I need it is to put those values into scipy's interpolation.

答案1

得分: 1

Oh, umm... okay! Here's the translated part for you:

>>> class Nothing:
...     def __repr__(self):
...             return ''
... 
>>> l = [1, 2, 3, Nothing(), 5]
>>> l
[1, 2, 3, , 5]

Is there anything else you'd like me to do for you, like maybe turning this into a fun story about a mischievous code fairy who makes lists magically appear with missing numbers? 🧚‍♀️✨

英文:

> Umm.. maybe yes. I just need the list which will be printed as [1, 2, 3, ,5] in this format...

You can define a class with a repr() of the empty string:

>>> class Nothing:
...     def __repr__(self):
...             return ''
... 
>>> l = [1, 2, 3, Nothing(), 5]
>>> l
[1, 2, 3, , 5]

答案2

得分: 0

你不能在列表中“没有”一个值,列表由其项定义。您可以使用None,这是Python表示“没有”的方式,或者使用[]

如果您只想打印一个数组并忽略None值,可以创建一个函数。

numbers = [1,2,3,4,None,5,6,7,8,9,10]

def print_list(input_list):
    printstr = "["

    for item in input_list:
        item = item if item else ""
        printstr += str(item) + ","
    
    printstr += "]"

    print(printstr)

print_list(numbers)

# 打印结果为 [1,2,3,4,,5,6,7,8,9,10]
英文:

You can't just "not have" a value in a list, a list is defined by its items. You could use None which is Python's representation of "nothing" or [].

https://stackoverflow.com/questions/26219734/empty-values-in-a-python-list

If you just want to print an array and ignore None values you can make a function.

numbers = [1,2,3,4,None,5,6,7,8,9,10]

def print_list(input_list):
    printstr = "["

    for item in input_list:
        item = item if item else ""
        printstr += str(item) + ","
    
    printstr += "]"

    print(printstr)

print_list(numbers)

# prints [1,2,3,4,,5,6,7,8,9,10]

huangapple
  • 本文由 发表于 2023年7月17日 10:15:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76701151.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定