[英]python: reading a file and storing strings as strings and integers as integers into a list
I am new to python and I've tried to look for this question everywhere but I couldn't find it I am not sure if this even works but here we go.....So I am trying to read a file with different types of variables and storing different regex into a list.我是 python 的新手,我试图到处寻找这个问题,但我找不到它我不确定这是否有效,但我们走了......所以我试图读取一个不同的文件变量类型并将不同的正则表达式存储到列表中。 Strings, floats, ints, keywords....etc all in a list, but they are all stored as strings in the list not different types.
字符串、浮点数、整数、关键字...等都在一个列表中,但它们都作为字符串存储在列表中,而不是不同的类型。
For example:例如:
list1 = ['sandy', 'mike', '3.2', '15']
I want it to be stored into the list like this:我希望它像这样存储到列表中:
list1 = ['sandy', 'mike', 3.2, 15]
It is very important for me to know which ones are strings and which ones are numbers.知道哪些是字符串哪些是数字对我来说非常重要。
I can't use dictionaries because they are not indexed plus they move around and I can't use tuples because they can't be "poped" off the stack, I can only use lists because they are indexed and I can use the pop method.我不能使用字典,因为它们没有被索引,而且它们会四处移动,我不能使用元组,因为它们不能从堆栈中“弹出”,我只能使用列表,因为它们已被索引,我可以使用弹出方法。
Is there away of doing this when reading in a file?读入文件时有没有这样做?
As I said in comment, you could simply change Ashwini Chaudhary's function to this:正如我在评论中所说,您可以简单地将Ashwini Chaudhary 的功能更改为:
def func(seq):
for x in seq:
try:
if '.' in x:
yield float(x)
else:
yield int(x)
except ValueError:
yield x
list1 = ['sandy', 'mike', '3.2', '15', '3.243', 'Washington D.C.']
for i in func(list1):
print(i)
print(type(i))
print()
Output:输出:
sandy
<class 'str'>
mike
<class 'str'>
3.2
<class 'float'>
15
<class 'int'>
3.243
<class 'float'>
Washington D.C.
<class 'str'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.