程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用特定条件将列表中的项目转换为 int (Python)大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决使用特定条件将列表中的项目转换为 int (Python)?

开发过程中遇到使用特定条件将列表中的项目转换为 int (Python)的问题如何解决?下面主要结合日常开发的经验,给出你关于使用特定条件将列表中的项目转换为 int (Python)的解决方法建议,希望对你解决使用特定条件将列表中的项目转换为 int (Python)有所启发或帮助;

我有一个由字符组成的字符串,所有这些字符都用逗号分隔,我想创建一个仅包含整数的列表。我写道:

str = '-4,5,170.5,4,s,k4,4k,1.3,8'.replace(' ','')
# Now the str without spaces: '-4,8'

lst_str = [item for item in str.split(',')
# Now I have a List with the all items: ['-4','5','170.5','4','s','k4','4k','1.3','8']

int_str = [num for num in lst_str if num.isdigit]
# The problem is with negative character and Strings like '4k'
# and 'k4' which I don't want,and my code doesn't work with them.

#I want this: ['-4','8'] which I can changed after any item to type int.

有人可以帮我怎么做吗?无需导入任何类。 我没有找到这个特定问题的答案(这是我的第一个问题)

解决方法

isdigit() 是一个函数,而不是属性。它应该用 () 调用。它也不适用于负数,您可以删除支票的减号

int_str = [num for num in lst_str if num.replace('-','').isdigit()]
# output: ['-4','5','4','8']

如果您需要避免出现 '-4-' 的情况,请使用出现次数参数

num.replace('-','',1)
,

试试这个:

def check_int(s):
    try: 
        int(s)
        return True
    except ValueError:
        return false
    
int_str = [num for num in lst_str if check_int(num)]
,

我是用这个做的:

String = '-400,5,170.5,4,s,k4,4k,1.3,8'.replace(' ','')
# Now the str without spaces: '-4,8'

let_str = [item for item in String.split(',')]
# Now I have a list with the all items: ['-4','170.5','s','k4','4k','1.3','8']
neg_int = [num for num in let_str if "-" in num]

int_str = [num for num in let_str if num.isdigit()]
neg_int = [num for num in neg_int if num[1:].isdigit()]

for num in neg_int: int_str.append(num)
print(int_str)
,

如果将它与 Python - How to convert only numbers in a mixed list into float? 结合起来,这与问题 python: extract Integers from mixed list 非常接近。

您的“过滤器”根本不过滤 - 名为 num.isdigit 的非空字符串实例上的函数 num 始终为真。

您使用整数代替浮点数:创建一个函数,尝试将某些内容解析为整数,如果没有则返回 None。 只保留那些不是 None 的。

text  = '-4,8'    
cleaned = [i.Strip() for i in text.split(',') if i.Strip()]

def tryParseInt(s):
    """Return Integer or None depending on input."""
    try:
        return int(s)
    except ValueError:
        return None

# create the Integers from Strings that are Integers,remove all others 
numbers = [tryParseInt(i) for i in cleaned if tryParseInt(i) is not None]

print(cleaned)
print(numbers)

输出:

['-4','8']
[-4,8]
,

正则表达式解决方案怎么样:

import re

str = '-4,8'
int_str = [num for num in re.split(',\s*',str) if re.match(r'^-?\d+$',num)]
,

你可以尝试用这个函数替换 num.isdigit :

def isnumber(str):
    try:
        int(str)
        return True
    except:
        return false

例:int_str = [num for num in lst_str if isnumber(num)]

大佬总结

以上是大佬教程为你收集整理的使用特定条件将列表中的项目转换为 int (Python)全部内容,希望文章能够帮你解决使用特定条件将列表中的项目转换为 int (Python)所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。