0

list1 = ['2019-01-02', 'NASDAQ', 'Apple Inc.', 'AAPL', '39.48', '148158800']

I want to change list1 as

list2 = ['2019-01-02', 'NASDAQ', 'Apple Inc.', 'AAPL', 39.48, 148158800]

Each type is str, str, str, str, float, int.

I have tried some codes, but only thing I can do is removing all the quotation marks.

Is there any other methods?

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
juna
  • 29
  • 2
  • 4
    " but only thing I can do is removing all the quotation marks." What. Either this means you were successful, or it means you *don't have a list in the first place*,but a string with all those symbols in it. It's important that you understand your data properly. We can't help you with your code unless we *see your actual code*, including the code that makes `list1` have this starting value. – Karl Knechtel Nov 28 '20 at 16:14
  • 1
    You should probably think about why you appear to be using a list in place of a (named) tuple or a class whose instances have attributes of varying types. – chepner Nov 28 '20 at 16:22
  • There's a difference between parsing a string to a number and "removing quotation marks". You'll need to differentiate the way a datatype is displayed and type it is and what's in it. It's not like strings have quotation marks necessarily--that's just syntax and display. Also, when trying code, please show it. – ggorlen Nov 28 '20 at 16:22

1 Answers1

0

A simple try and catch will suffice here.

import numpy as np 
list1 = ['2019-01-02', 'NASDAQ', 'Apple Inc.', 'AAPL', '39.48', '148158800',np.nan]
list2 = []
for ele in list1:
    try:
        if float(ele).is_integer():
            list2.append(int(ele))
        else:
            list2.append(float(ele))
    except ValueError:
        list2.append(ele)
print(list2)
>>> ['2019-01-02', 'NASDAQ', 'Apple Inc.', 'AAPL', 39.48, 148158800, nan]
Equinox
  • 6,483
  • 3
  • 23
  • 32
  • be aware that you are converting int to float. You shoild probably try int() conversion first – farincz Nov 28 '20 at 16:24
  • the final 148158800 has to be in a int type... how can i convert into int, not float? – juna Nov 28 '20 at 16:26
  • Here's the problem: there's a fund whose stock symbol is [`NAN`](https://finance.yahoo.com/quote/NAN); `float('NAN')` will return a valid IEEE not-a-number value rather than raising the exception you assume it will raise. You can't just blindly assume that anything that *could* be a float *should* be a float. – chepner Nov 28 '20 at 16:26
  • Updated my answer to have integers converted safely. – Equinox Nov 28 '20 at 16:31
  • @chepner agreed. OP can probably do some tinkering on his end to handle edge cases if `NAN` is part of his data. – Equinox Nov 28 '20 at 16:33