简体   繁体   English

将字符串转换为列表并将元素转换为整数

[英]Convert a string to a list and convert the elements to integers

So I have a string and I want to convert it to a list 所以我有一个字符串,我想将其转换为列表

input: 输入:

"123|456|890|60"

output: 输出:

[123,456,890,60]

Another example, input: 另一个例子,输入:

"123"

output: 输出:

[123]

Here is what I did until now. 这是我到目前为止所做的。

A=input()
n=len(A)
i=0
z=0
K=""
Y=[0]*n
while(i<n):
  if(A[i]=="|"):
    Y[z]=int(Y[z])
    j=+1
    K=""
  else:
    Y[z]=K+A[i]
  i+=1
print(Y)

Thanks for editing in your attempt. 感谢您的修改。 Splitting a string and converting a string to an integer are very common tasks, and Python has built in tools to achieve them. 拆分字符串并将字符串转换为整数是非常常见的任务,Python内置了实现这些功能的工具。

str.split splits a string into a list by a given delimiter. str.split通过给定的分隔符将字符串拆分为列表。 int can convert a string to an integer. int可以将字符串转换为整数。 You can use map to apply a function to all elements of a list. 您可以使用map将功能应用于列表的所有元素。

>>> map(int, "123|456|890|60".split('|'))
[123, 456, 890, 60]

Using list comprehension 使用list comprehension

Code: 码:

[int(a) for a in "123|456|890|60".split("|")]

Output: 输出:

[123, 456, 890, 60]

Notes: 笔记:

  • Split creates a list of strings here where the current strings are split at | 拆分在此处创建一个list of strings其中当前字符串在|拆分。
  • We are looping over the list and converting the strings into int 我们正在遍历列表并将字符串转换为int

Here's a similar approach, using regular expressions instead: 这是一种类似的方法,而是使用正则表达式:

import re

def convert_string(s):
    return map(int, re.findall(r'[0-9]+', s))    

Or using a list comprehension: 或使用列表推导:

import re

def convert_string(s):
    return [int(num) for num in re.findall(r'[0-9]+', s)]

This is a more general approach and will work for any character (in this case '|') that separates the numbers in the input string. 这是一种更通用的方法,适用于将输入字符串中的数字分隔开的任何字符(在本例中为“ |”)。

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

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