简体   繁体   English

如何在Python中将具有数字和字符的列表中的数字仅转换为int

[英]How to convert only the numbers to int in a list that has numbers and char in Python

I am learning Python and while practicing, I have this type of input: 我正在学习Python,在练习时,我会收到以下类型的输入:

  • 1 2 3 4 S 1 2 3 4秒
  • 3 4 5 6 N 3 4 5 6 N
  • 3 4 1 8 S 3 4 1 8秒

It will always be a set of numbers separeted by space and end with a letter (char). 它始终是一组由空格分隔并以字母(char)结尾的数字。 I am reading it with input() and making it a list like this 我正在用input()阅读它,并使其成为这样的列表

data = input()
myList = data.split()

What I want is to take the list and put only the numbers to a new list. 我想要的是获取列表,然后仅将数字添加到新列表中。 I tried this, but it only works if the list only has int values: 我试过了,但是仅在列表中只有int值时才有效:

myList = [int(i) for i in myList]

How can I only take the int values and put them in a new list. 我如何只将int值放入新列表中。

NOTE: My data input always ends with a letter but it will be nice if I someone gives a solution where there are letters at any random index of the list. 注意:我的数据输入总是以字母结尾,但是如果有人给出一种解决方案,其中列表的任何随机索引处都有字母,那将很好。 Thanks in advance 提前致谢

您只需要向理解添加过滤器。

msj = [int(i) for i in msg if i.isdigit()]

I would do it like this 我会这样

new_list = []
for item in myList:
    if item.isdigit():
        new_list.append(int(item))

您可以利用以下事实:字母始终出现在字符串的末尾:

newList =  [int(n) for n in myList[:-1]]

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

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