How do I iterate this list? - python

All I have is one list like below:
list = [ [{u'name': u'Peter'} , {u'name': u'Kevin'} , {u'name': u'Earl'}] ]
I need to get Peter Kevin Earl separately and use that as a parameter to query. How do I write my for loop?
I think there is one list in my list and inside the list has three dictionaries. I need to fetch per dictionary's value.

This would do the trick:
inner_values = [dictionary.values()[0] for dictionary in list[0]]
This solution will get you value out of the inner maps no matter what the key is.

lst = [[{u'name': u'Peter'}, {u'name': u'Kevin'}, {u'name': u'Earl'}]] # Note that this is a list containing another list, containing dictionaries.
names = [x["name"] for x in lst[0]]
I had to change your original list, because "Earl" was listed as a number. :)

first_list = [[{u'name': u'Peter'},{u'name': u'Kevin'},{u'name': u'Earl'}]]
names = []
# You loop over the whole list
for element in first_list:
# For each element, you loop over the elements inside it
for object in element:
# Now, object is each one of the dictionaries
names.append(object["name"])
The code above should works, and here you have a more pythonic answer
# By list comprehension
names = [ x["name"] for x in temp_list for temp_list in first_list ]
# If you don't know the how the key is named
names = [ x.values()[0] for x in temp_list for temp_list in first_list ]
It doesn't matter how many lists you have inside the first list because you are looping over it. And if there is only a list, the loop will iterate once.

Related

Changing elements of list to string

I have a list [['user44'],['user204'],['user355'],['user395'],['user452']]
I want to convert it to [ 'user44', 'user204' , 'user355', 'user395', 'user452']
Any help on this?
Assuming userXYZ is always a string
lst = [['user44'],['user204'],['user355'],['user395'],['user452']]
lst1 = [y for x in lst for y in x]
print(lst1)
output
['user44', 'user204', 'user355', 'user395', 'user452']
Every element of the list is a list itself, with one element.
You can take that element and create a new list using list comprehension.
new_list=[elem[0] for elem in old_list]
This will go over all elements of the list (which are themselves, lists), and extract the strings into a new list.
This will allow for use encase you need to join more than 1 list.
x = [''.join(x[i] for i in range(len(x)))]

How to make a list to split into each element and make a sublist

If I have this list,
list01 = ['GAGGT','TCCGT','ABECF']
I want to make each element in the list to split, but still remain in the same box of list.
Like this:
listalt = [['G','A','G','G','T'],['T','C','C','G','T'],['A','B','E','C','F']]
listalt = [list(i) for i in list01]
This is a list comprehension, and uses the fact that list can take an iterable (like a string) and turn it into a list
You can use this :
final_list=[]
for item in list01:
final_list.append(list(item))
print(final_list)
which is same as :
print([list(item) for item in list01])

Remove item from a list element?

This may seem odd, but I am trying to remove a part of an item contained in a list. Basically, I am trying to remove a specific character from multiple list elements. For example
list = ['c1','c2','c3','d1','s1']
list.remove('c')
I know that doing that wouldn't work, but is there any way to remove the "c"s in the list, and only the "c"s in Python 3?
lst = [s.replace('c','') for s in lst]
# ['1','2','3','d1','s1']
List comprehensions are your friend. Also note the "list" is a keyword in Python, so I highly recommend you do not use it as a variable name.
Use list comprehensions,
list = ['c1','c2','c3','d1','s1']
list_ = [ x for x in list if "c" not in x ] # removes elements which has "c"
print list_ # ['d1', 's1']
list1 = ['c1','c2','c3','d1','d2']
list2 = []
for i in range (len(list1)):
if 'c' not in list1[i]:
list2.append(list1[i])
print (list2) #['d1', 'd2']
and also this link may helpful
Link one

Put average of nested list values into new list

I have the following list:
x = [(27.3703703703704, 2.5679012345679, 5.67901234567901,
6.97530864197531, 1.90123456790123, 0.740740740740741,
0.440136054421769, 0.867718446601942),
(25.2608695652174, 1.73913043478261, 6.07246376811594,
7.3768115942029, 1.57971014492754, 0.710144927536232,
0.4875, 0.710227272727273)]
I'm looking for a way to get the average of each of the lists nested within the main list, and create a new list of the averages. So in the case of the above list, the output would be something like:
[[26.315],[2.145],[5.87],etc...]
I would like to apply this formula regardless of the amount of lists nested within the main list.
I assume your list of tuples of one-element lists is looking for the sum of each unpacked element inside the tuple, and a list of those options. If that's not what you're looking for, this won't work.
result = [sum([sublst[0] for sublst in tup])/len(tup) for tup in x]
EDIT to match changed question
result = [sum(tup)/len(tup) for tup in x]
EDIT to match your even-further changed question
result = [[sum(tup)/len(tup)] for tup in x]
An easy way to acheive this is:
means = [] # Defines a new empty list
for sublist in x: # iterates over the tuples in your list
means.append([sum(sublist)/len(sublist)]) # Put the mean of the sublist in the means list
This will work no matter how many sublists are in your list.
I would advise you read a bit on list comprehensions:
https://docs.python.org/2/tutorial/datastructures.html
It looks like you're looking for the zip function:
[sum(l)/len(l) for l in zip(*x)]
zip combines a collection of tuples or lists pairwise, which looks like what you want for your averages. then you just use sum()/len() to compute the average of each pair.
*x notation means pass the list as though it were individual arguments, i.e. as if you called: zip(x[0], x[1], ..., x[len(x)-1])
r = [[sum(i)/len(i)] for i in x]

Using two lists to define a variable in python

I have two lists that have a relationship with each other. List1 is descriptors and List2 is rankings of those descriptions
list1 = ["String1", "String2", "String3"]
list2 = ["2", "1", "3"]
What I want to be able to do is create variables that link these up. So if I want to print ranking number 1, I would get what was originally string2.
What's the best way to approach this?
Use a dictionary, such as
content = {"2":"String1", "1":"String2", "3":"String3"}
print content["1"]
If you would like to generate the dic from list, you could:
content = dict((key, value) for (key, value) in zip(list2, list1))
Thanks to #minitech, a much more beautiful statement would be:
content = dict(zip(list2, list1))
You could try a dictionary. Dicionaries contain key:value pairs:
rankings = {"1":"String2", "2":"String1", "3":"String3"}
then you can access the elements like:
print rankings["1"]
it will print
"String2"
But how to create this dictionary? Use a for loop (assuming list1 and list2 have the same length)
rankings = {} # Create empy dicionary
for i in range(len(list2)): # Loop 'n' times, where 'n' is the length of the lists
rankings[list2[i]] = list1[i]
Note: Depending in your implementation, you could just use a number, instead of a string as key in the dictionary:
rankings = {1:"String2", 2:"String1", 3:"String3"}

Categories

Resources