且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将逗号分隔的字符串转换为列表

更新时间:2023-09-06 20:08:58

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

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".

此外,如果您想使用整数而不是子字符串,则需要进行这种转换。

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]