I need to convert a list of lists (containing strings) into a simple list of integers. I have
mylist = [["14"],["2"],["75"],["15"]]
I need
newlist = [14, 2, 75, 15]
Thank you
You need to do two things with your list — flatten it out and then convert the strings to int. Flattening it is easy with itertools.chain. After that you can use map() to apply int to each item:
from itertools import chain
mylist = [["14"],["2"],["75"],["15"]]
newest = list(map(int, chain.from_iterable(mylist)))
# newest is => [14, 2, 75, 15]
This will work even if your lists have more than one item like: [["14", "15"],["2"],["75"],["15"]]
Just use a list comprehension
>>> mylist = [["14"],["2"],["75"],["15"]]
>>> [int(item[0]) for item in mylist]
[14, 2, 75, 15]
Dictionary needs key and value pairs. That means a dictionary of Dictionaries has key and dictionary(as a value) pairs.
dictofd = {{'name': 'jay', 'age': '78', ... }, {'name': 'kay', 'age': '32', ... },...}
This does not have keys. Therefore, you should use an array of dictionaries or set of dictionaries. If you have to use a dictionary, make some (artificial) keys like the below.
dictofd = { 1: {'name': 'jay', 'age': '78', ... }, 2: {'name': 'kay', 'age': '32', ... }, ...}
If your sublists might have more than one item, a nice list comprehention solution is:
newlist = [int(str) for sublist in mylist for str in sublist]
You can also refer to this article for more explanation and examples.
To achive this we have multiple ways to do,few examples are:
Using List Comprehension:
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = [element for sublist in list_of_lists for element in sublist]
print(flattened_list)
Using itertools.chain:
import itertools
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = list(itertools.chain(*list_of_lists))
print(flattened_list)
Using sum() with List Comprehension:
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = sum(list_of_lists, [])
print(flattened_list)
All these methods will produce the same output:
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
setof dictionaries? What you've mentioned in the "would need" section is aset, not adictionary.dictofd?