将逗号分隔的字符串转换为列表[重复]

时间:2021-06-19 00:20:27

This question already has an answer here:

这个问题在这里已有答案:

I want to store a list of integers as a field in my model. As there is no field provided for this by default in Django, I am doing it by using a CommaSeparatedIntegerField called x. In my view, I then take this string and create a list of integers from it. When a model instance is created with parameter n, I want x to be set to length n, with each element being set to zero.

我想将整数列表存储为模型中的字段。由于Django默认没有为此提供任何字段,因此我使用名为x的CommaSeparatedIntegerField进行此操作。在我看来,然后我接受这个字符串并从中创建一个整数列表。当使用参数n创建模型实例时,我希望将x设置为length n,并将每个元素设置为零。

Here's the model:

这是模型:

class Foo(models.Model):
    id = models.IntegerField(default = 0)
    x = models.CommaSeparatedIntegerField(max_length = 10)

@classmethod
def create(cls, _id, n):
    user = cls(id = _id)
    user.class_num_shown = '0,' * n

Then I create an instance:

然后我创建一个实例:

f = Foo.create(1, 4)
f.save()

And load it from the database and convert the string into a list:

并从数据库加载它并将字符串转换为列表:

f = Foo.objects.get(id = 1)
x_string = f.x
x_list = x_string.split(',')
print x_list

But this outputs [u'0,0,0,0,'] rather than what I want, which would be [0,0,0,0]. How can I achieve my desired output?

但这输出[u'0,0,0,0,']而不是我想要的,这将是[0,0,0,0]。如何实现我想要的输出?

2 个解决方案

#1


4  

The separator argument for split() is not a list of different characters to split on, but rather the entire delimiter. Your code will only split occurrences of "comma space".

split()的separator参数不是要拆分的不同字符的列表,而是整个分隔符。您的代码只会拆分出现“逗号空间”。

Further, if you want integers instead of substrings, you need to do that conversion.

此外,如果您想要整数而不是子串,则需要进行转换。

Finally, because you have a trailing comma, you need to filter empty results from your split.

最后,因为您有一个尾随逗号,您需要从拆分中过滤掉空结果。

>>> data = '0,0,0,0,'
>>> values = [int(x) for x in data.split(',') if x]
>>> values
[0, 0, 0, 0]

#2


4  

values = map(int, '0,1,2,3,'.rstrip(',').split(','))

#1


4  

The separator argument for split() is not a list of different characters to split on, but rather the entire delimiter. Your code will only split occurrences of "comma space".

split()的separator参数不是要拆分的不同字符的列表,而是整个分隔符。您的代码只会拆分出现“逗号空间”。

Further, if you want integers instead of substrings, you need to do that conversion.

此外,如果您想要整数而不是子串,则需要进行转换。

Finally, because you have a trailing comma, you need to filter empty results from your split.

最后,因为您有一个尾随逗号,您需要从拆分中过滤掉空结果。

>>> data = '0,0,0,0,'
>>> values = [int(x) for x in data.split(',') if x]
>>> values
[0, 0, 0, 0]

#2


4  

values = map(int, '0,1,2,3,'.rstrip(',').split(','))