简体   繁体   English

Python:将List中的Float转换为Int

[英]Python: Convert Float to Int in List

I'm trying to retrieve values from a list, and if the value can be converted to int, I want to store the value as int in a string.我正在尝试从列表中检索值,如果该值可以转换为 int,我想将该值作为 int 存储在字符串中。 For this, I have tried to use int() and try...except blocks, but still my is not getting converted to int.为此,我尝试使用 int() 和 try...except 块,但我的仍然没有转换为 int。

My code:我的代码:

_number_of_alphabets, _number_of_numbers, _number_of_special_characters = ranges(_size,_number_of_alphabets,_number_of_numbers,_number_of_special_characters)
    _list = alphabets(_number_of_alphabets)
    _list = append(_list,numbers(_number_of_numbers))
    _list = append(_list,special_characters(_number_of_special_characters))
    shuffle(_list)
 
    _password = ''
 
    for i in _list:
        try:
            _password+=int(i)
        except:
            _password+=i
    
    return _password

Can anyone please help me to understand, how should I modify my code so that _password store the list items that can be converted to int as int and store remaining values as it is任何人都可以帮助我理解,我应该如何修改我的代码,以便 _password 将可以转换为 int 的列表项存储为 int 并按原样存储剩余值

Please try to provide full error traceback documentation in future posts to help people better assist you.请尝试在以后的帖子中提供完整的错误回溯文档,以帮助人们更好地帮助您。

It's fundamentally impossible to concatenate type int to a str initialization unless you cast the int as a str (ie, the opposite of what you're trying to do).基本上不可能将类型int连接到str初始化,除非您将int转换为str (即,与您尝试做的相反)。 I'm not really sure what your end goal is here, but I can assure you that the problem is not that the strings which you are trying to cast as integers are not being converted (in the case where they are numbers in string form), it's rather just that you can't concatenate them to an empty string.我不太确定你的最终目标是什么,但我可以向你保证,问题不在于你试图转换为整数的字符串没有被转换(在它们是字符串形式的数字的情况下) ,只是你不能将它们连接到一个空字符串。

If there's something else you're trying to do here, I can try to help if you can elaborate.如果您想在这里做其他事情,如果您能详细说明,我会尽力提供帮助。

L = [some float numbers separated by comma]
New_l = []
for I in L:
    New_l.append(int(I)) 

Code is pretty much self explanatory代码几乎是不言自明的

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

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