![]() ![]() As can be seen from the following performance plot, map() outperforms list comprehension regardless of list size. Map() is about 64% faster than the list comprehension. With minor adjustments, we can make it handle floats too but that's a separate topic. User-defined function to convert a string into integer def stringtoint(inputstring): outputint 0 Check if the number contains any minus sign or not, i.e. ![]() 1e3) can also be a valid integer, in that case, we can add another condition to the comprehension (albeit less legible): )*10**int(e) if (e:=x.split('e',1)) and e.isdecimal() else float('nan') for x in lst]įor lst =, the above comprehension returns. It is essentially checking if a value is decimal or not (either negative or positive). If you want to set these invalid values to NaN and convert the valid values in the list (similar to how pandas' to_numeric behaves), you can do so using the following list comprehension: Int() raises an error if an invalid value is fed. Method #3 : Using map() # Python3 code to demonstrate Method #2 : Using list comprehension # Python3 code to demonstrate Print ("Modified list is : " + str(test_list)) Print ("Original list is : " + str(test_list)) Method #1 : Naive Method # Python3 code to demonstrate I also want to add Python | Converting all strings in list to integers Things like, 3.141), 'types'] # sets are unordered, hence diffrent order ) to itself in output.ĭoes not work for Mappings - you would need to check abc.Mapping and handle """Tries to convert an iterable to list of floats, ints or the original thingįrom the iterable. To also handle iterables inside iterables you can use this helper: from collections.abc import Iterable, Mapping """Returns a string 's' into a integer if possible, a float if needed orĭata = Ĭonverted = list(map(maybeMakeNumber, data)) So: if you have data that may contain ints, possibly floats or other things as well - you can leverage your own function with errorhandling: def maybeMakeNumber(s): It will crash if you give it things that are not integers. If your list contains pure integer strings, the accepted answer is the way to go. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |