如何在Python中将字符串拆分为列表?

时间:2018-04-16 07:45:54

标签: python

这里我的字符串看起来像List<String> received = insert_code_for_get_call_here(); List<String> sorted = received.stream().sorted().collect(Collectors.toList()); assertEquals(sorted, received); 我想把它变成这样的列表 [128,120,119,118,119,118,120,116,116,120,128,121]

所以我曾在python中尝试过命令'list',使其成为一个列表

但是,结果看起来像'128,120,119,118,119,118,120,116,116,120,128,121'

虽然字符串数据的类型是list,但切割点是错误的。

6 个答案:

答案 0 :(得分:4)

使用Split方法

>>> s = '128,120,119,118,119,118,120,116,116,120,128,121'
>>> l = s.split(',') # Split with ','
>>> [int(i) for i in l] # Change str to int type, *Used list comprehensions
[128, 120, 119, 118, 119, 118, 120, 116, 116, 120, 128, 121]
>>> 

答案 1 :(得分:2)

Private Sub MyUserControl_Load(sender As Object, e As EventArgs) Handles MyBase.Load Dim _Count As Integer Dim _UserControl As MyUserControl For Each _UserControl In Me.ParentForm.Controls If _UserControl.Name.Contains("MyUserControl") Then _Count += 1 End If Next If _Count > 1 Then MsgBox("Control have been placed.") Else MsgBox("Control haven't placed yet.") End If End Sub 功能在这里会有所帮助。

str.split()

论证是你想要分割的角色。

PS。如果您想要分割多个字符,请在字母表中以逗号和空格分隔,例如nums = '128,120,119,118,119,118,120,116,116,120,128,121' num_list = nums.split(',') ,您可以使用nums = '128, 120, 119, 118, 119, 118, 120, 116, 116, 120, 128, 121'

答案 2 :(得分:2)

a = '128,120,119,118,119,118,120,116,116,120,128,121'

b = [int(l) for l in a.split(',')]

答案 3 :(得分:1)

您可以使用split方法。

my_string = "128,120,119,118,119,118,120,116,116,120,128,121"
my_list = my_string.split(",")

print my_list

输出:

  

[&#39; 128&#39;&#39; 120&#39;&#39; 119&#39;&#39; 118&#39;&#39; 119&#39;,& #39; 118&#39;&#39; 120&#39;&#39; 116&#39;&#39; 116&#39;&#39; 120&#39;&#39; 128&# 39;,&#39; 121&#39;]

答案 4 :(得分:0)

您可以根据,进行拆分,以便根据需要获取列表。

但请记住,该列表是一个字符串列表,即数字128将字符串'128'。

要获取整数列表,您需要将此字符串列表转换为整数列表。

您可以执行此操作,如下所示。

num_string = '128,120,119,118,119,118,120,116,116,120,128,121'

string_list = num_string.split(',')

int_list = [int(x) for x in string_list]

print(int_list)

答案 5 :(得分:0)

添加一个简单的声明:

  

d = [int(c)表示b中的c]

其中b = [&#39; 1&#39;,&#39; 2&#39;,....]