简体   繁体   中英

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. 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:

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'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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