How to access certain elements of a list of lists? - python

I'm not sure what I need to do here.
I have a list which contains sublists:
my_list = [
[string_0, string2, [int1, int2], [int3, float1]],
[string_01, string2_2, [int1_1, int2_2], [int3_3, float1_1]]
]
which goes on like this for a bit.
How do I get certain parts from my_list to create a new list containing certain items from my_list? For example:
new_list = [string_01, string2, int1, float1_1]
So far I was trying to use a list comprehension but I couldn't get it to work because I only got it to print one sublist (ie: string_0, string2, [int1, int2], [int3, float1]) and not specific parts.

To get the elements you showed in your example:
new_list=[ [i[0], i[1], i[2][0], i[3][1] ] for i in my_list]
print (new_list)

Related

How to return all item in list of lists that are not in other list of lists in Python?

I have 2 list of lists:
list1: [[1,2,3],[2,5],[6,7,4]]
list2: [[1,3],[2],[6,4],[9,0,3]]
I want to do few things:
Find every number that is in list 1 but is not in list 2, store it in a new list, and then append this new list to list2.
In our case: new_list = [5,7]
and then, we will add it to list2 = [[1,3],[2],[6,4],[9,0,3],[5,7]]
Then, I want to remove duplicates of numbers from each list1 and list 2:
In our case: list1 = [[1,3],[2,5],[6,7,4]], list2 = [[1],[2],[6,4],[9,0,3],[5,7]]
I have an implementation using For loops, but I need something more elegant for that.
Can you help me please find out a way?
Using Python, you can do the first part with a set comprehension:
list2.append(list({i for j in list1 for i in j}.difference({i for j in list2 for i in j})))

Getting the values of a dictionary contained in a list of lists

Having a list like:
my_list = [
[{'score':9, 'name':'Jack'}],
[{'score':3, 'name':'Danielle'}]
]
I am trying to iterate through this list but can't figure out how to access the values.
for listing in my_list:
print(listing['score'])
The above does not work. Which I understand as I seem to be working on a dictionary that is still inside the second list. However, I am having trouble finding out the correct way to do get access.
You can try this by matching exact the signature of the inner elements. This is called tuple unpacking
my_list = [
[{'score':9, 'name':'Jack'}],
[{'score':3, 'name':'Danielle'}]
]
for [listing] in my_list:
print(listing['score'])
# 9
# 3
You are using the wrong syntax for python dictionaries.
Python dictionaries are declared between {...}.
Your list should look like:
my_list = [
{'score':9, 'name':'Jack'},
{'score':3, 'name':'Danielle'}
]
EDIT:
In your edit you have a list within a list. Try
for listing in my_list:
print(listing[0]['score'])
What are you creating is a 2D List, you need Dictionaries inside that
my_list = [
{'score':9, 'name':'Jack'},
{'score':3, 'name':'Danielle'}
]
for listing in my_list:
print(listing['score'])
You need 2 loops, one for the outer list, and one for the inner list:
my_list = [
[{'score':9, 'name':'Jack'}],
[{'score':3, 'name':'Danielle'}]
]
for sublist in my_list:
for dct in sublist:
print(dct['score'])
# 9
# 3
You can also use nested list comprehension:
print([dct['score'] for sublist in my_list for dct in sublist])
# [9, 3]
You need to create the items inside your list with {} rather than [].
my_list = [
{'score':9, 'name':'Jack'},
{'score':3, 'name':'Danielle'}
]
[] will create a list, while {} will create a dict.

Join elements of an arbitrary number of lists into one list of strings python

I want to join the elements of two lists into one list and add some characters, like so:
list_1 = ['some1','some2','some3']
list_2 = ['thing1','thing2','thing3']
joined_list = ['some1_thing1', 'some2_thing2', 'some3_thing3']
however i don't know in advance how many lists I will have to do this for, i.e. I want to do this for an arbitrary number of lists
Also, I currently receive a list in the following form:
list_A = [('some1','thing1'),('some2','thing2'),('some3','thing3')]
so I split it up into lists like so:
list_B = [i for i in zip(*list_A)]
I do this because sometimes I have an int instead of a string
list_A = [('some1','thing1',32),('some1','thing1',42),('some2','thing3', 52)]
so I can do this after
list_C = [list(map(str,list_B[i])) for i in range(0,len(list_B)]
and basically list_1 and list_2 are the elements of list_C.
So is there a more efficient way to do all this ?
Try this if you are using python>=3.6:
[f'{i}_{j}' for i,j in zip(list_1, list_2)]
If you using python3.5, you can do this:
['{}_{}'.format(i,j) for i,j in zip(list_1, list_2)]
also you can use this if you don't want to use formatted string:
['_'.join([i,j]) for i,j in zip(list_1, list_2)]
You can join function like this on the base list_A, itself, no need to split it for probable int values:
list_A = [('some1','thing1',32),('some1','thing1',42), ('some2','thing3', 52)]
["_".join(map(str, i)) for i in list_A]
Output:
['some1_thing1_32', 'some1_thing1_42', 'some2_thing3_52']
Update:
For you requirement, where you want to ignore last element for last tuple in your list_A, need to add if-else condition inside the list-comprehension as below:
["_".join(map(str, i)) if list_A.index(i) != len(list_A)-1 else "_".join(map(str, i[:-1])) for i in list_A ]
Updated Output:
['some1_thing1_32', 'some1_thing1_42', 'some2_thing3']
For ignoring the last element of every tuple in list_A, I found this to be the quickest way:
["_".join(map(str, i)) for i in [x[:-1] for x in list_A] ]

Python : Checking if a string does not exist in a list of lists

I have a simple code that generates a list of lists and populates it with string "null", however when I try to check if "null" doesn't exist in the entire list of lists, it doesn't give me the result I'm expecting
lst = [ ['null']*4 for n in xrange(2) ]
print lst
if ('null' not in lst):
print "testing"
This code always prints "testing" and I don't know why.
Your explanation is appreciated
Thanks
Your list lst is not a list of strings but a list of lists of strings.
You might try:
if any('null' in lst2 for lst2 in lst):
as your test: that is, return True if there is a string 'null' in any of the sublists of your main list, lst.
flatten the list and then do a "is not in" check on the flattened list:
flattened = [x for x in sublist for sublist in lst]
if "null" not in flattened:
print("testing")

replace substrings in list

I am looking forward to get rid of a space that is after each element in my list:
list1 = ['Aena', 'Cellnex Telecom', 'Amadeus', 'Abertis']
in order to obtain the list like this:
list1 = ['Aena','Cellnex Telecom','Amadeus','Abertis']
I have tried the following loop but returns the same initial list:
new_list = [stocks.replace(" ","") for stocks in list1]
and
new_list = [stocks.replace(", '",",'") for stocks in list1]
print(new_list)
Could anyone help me to obtain the desired list without the spaces?
I think you have to understand, that print(..) prints the representation of a list (which is a comma separated list surrounded by square brackets).
With the list comprehension, you alter the elements themselves. As far as I know you can't do much about how print prints the list itself. But you can write your own print method.
We can do this by using a join on the repr(..) of the elements, and surround it by square brackets, like:
print('[{}]'.format(','.join(repr(x) for x in list1)))
This prints:
>>> print('[{}]'.format(','.join(repr(x) for x in list1)))
['Aena','Cellnex Telecom','Amadeus','Abertis']
>>> print('[{}]'.format(','.join(repr(x) for x in list1)))
['Aena','Cellnex Telecom','Amadeus','Abertis']

Categories