Working with lists - Python - python

i ran into a little logic problem and trying to figure it out.
my case is as follows:
i have a list of items each item represents a Group
i need to create a set of nested groups,
so, for example:
myGroups = ["head", "neck", "arms", "legs"]
i need to get them to be represented like this:
(if you can imaging a folder structure)
head
|_> neck
|_> arms
|_>legs
and so on until i hit the last element.
what i thought would work (but don't know really how to advance here) is:
def createVNTgroups(self, groupsData):
for i in range(len(groupsData)):
print groupsData[i]
for q in range(1, len(groupsData)):
print groupsData[q]
but in this case, i am running over same elements in 'i' that i already took with 'q'.
could someone give me a hint?
thanks in advance!

If I understood well, you want a nested structure. For this case, you can use a recursive function:
myGroups = ["head", "neck", "arms", "legs"]
def createVNTgroups(alist):
temp = alist[:] # needed because lists are mutable
first = [temp.pop(0)] # extract first element from list
if temp: # if the list still contains more items,
second = [createVNTgroups(temp)] # do it recursively
return first + second # returning the second object attached to the first.
else: # Otherwise,
return first # return the last element
print createVNTgroups(myGroups)
this produces a nested list:
['head', ['neck', ['arms', ['legs']]]]

Is that what you were looking for?
>>> m
['head', 'neck', 'arms', 'legs']
>>> reduce(lambda x,y:[x,y][::-1] if x!=y else [x], m[::-1],m[-1])
['head', ['neck', ['arms', ['legs']]]]

Related

How do I index f.items()?

I could run a for loop as such:
for v in f.items():
BUT, it takes too much time. I know I want the second object in f.items(). How to I directly get the second object and save it?
Im not sure what the syntax is: e.g is it f.items(2), f.items()[2]? None of these work so I was wondering what does.
If you want values(your 2nd objects) from f.items() you should use the below: -
for k,v in f.items()
Or if you want the 2nd item from f.items() you should use the below: -
f = {1:'A',2:'B',3:'C'}
for item in enumerate(f.items(),1):
k,v = item
if k == 2:
print(v)
Do still want to extract 2nd value from 2nd item ?
You can create a list and then index.
item = list(f.items())[1]
Lists are created often in python and this operation is relatively inexpensive. If your dictionary is large, you can create an iterator and take its second value.
i = iter(f.items())
next(i)
item = next(i)
But the dict would need to be rather large to make this the better option.

Hashing String List Elements and Saving to a New List

I'm trying to take 100 names, hash each name to 8 bits and save it to a new list. I understand that using 8 bits will most likely result in collisions, I'm trying to see at what rate they will collide and I'm hoping to include this code snippet in my paper.
I believe my logic is okay, it's just syntax that's causing my issues. Any help is appreciated.
import hashlib
list = ["Cammy", "Maisha", "Lizette", "Marjorie", "Shaquita", "Rueben", "Fatima", "Maynard",
"Laurena", "Lauren", "Allyson", "Pearlie", "Bethel", "Daniell", "Laurinda", "Crista",
"Ching", "Kareen", "Beth", "Stephnie", "Manie", "Kareem", "Titus", "Humberto",
"Lauretta", "Rob", "Raul", "Damion", "Stephani", "Carin", "Sharla", "Eleonor", "Naida",
"Ashley", "Rachel", "Graig", "Raymonde", "Shalanda", "Annetta", "Lissette", "Sandi",
"Alda", "Arlinda", "Ashlee", "Marguerite", "Tammi", "Denisha", "Genie", "Elizbeth",
"Elvie", "Markus", "Marquitta", "Arla", "Vanda", "Devon", "Meagan", "Taryn", "Lina",
"Shea", "Leighann", "Janel", "Sanora", "Harmony", "Concetta", "Dwayne", "Kyla",
"Evonne", "Mauro", "Deane", "Chester", "Inez", "Tari", "Maribeth", "Ariel", "Elisa",
"Maurice", "Dung", "Mona", "Hung", "Maximina", "Demarcus", "Jayson", "Jenny", "Duane",
"Reginia", "Gennie", "Orval", "Venus", "Craig", "Lessie", "Madaline", "Paulina",
"Aletha", "Gisele", "Sheena", "Devora", "Arcelia", "Ericka", "Colene", "Hildegard"]
newlist = []
for i in list:
newlist = hash(list[i] % 10**8)
for i in newlist:
print(i)
Without touching your logic, to make your code work you want to replace these lines:
for i in list:
newlist = hash(list[i] % 10**8)
with
for i in list:
newlist.append(hash(i) % 10**8)
Some clarification:
In Python, you can use .append() on any list object to add elements to the end of that list. In this case, you're filling the empty list you initialized above with elements inside a loop. Further, other than in e.g. a classic Java loop, in Python you can iterate over a list directly, such that your i refers to a different element of the list each time. Thus, there is no need to try and access the list at a certain index each time. Hope this helps!

Deleting every item in a list corresponding to match in other list

I am showing two cases of many such cases to explain the problem. Each case
has two lists. First list i.e. nu contains elements ID , which has to be matched with first element of every tuple in second list i.e. nu_ew.
If the match is found, I want to delete every occurrence of tuple with same ID from the second list i.e. nu_ew.
Issue is that I am successfully able to delete all desired element (tuple) from Case-2, but last occurrence of element (tuple) i.e. ('Na23', 0.0078838) corresponding to last ID in nu remains undeleted in Case-1.
I am looking for any way out to get desired result. Any suggestion is greatly appreciated.
Case-1:
nu=['F19', 'U234', 'U235', 'U238', 'Cl35', 'Cl37', 'Na23']
nu_ew = [('Mg24', 0.070385), ('Mg25', 0.0092824),
('Mg26', 0.0106276), ('F19', 0.42348),
('U234', 1.083506277), ('U235', 0.0014516),
('U238', 0.202605), ('Cl35', 0.0454252),
('Cl37', 0.0153641), ('Na23', 0.047303),
('F19', 0.0521210), ('U234', 3.61168759),
('U235', 0.000483890), ('U238', 0.067535),
('F19', 0.0217170), ('Na23', 0.0078838),
('Cl35', 0.0181700), ('Cl37', 0.0061456)]
Case-2:
nu=['F19', 'U234', 'U235', 'U238']
nu_ew = [('Mg24', 0.068893), ('Mg25', 0.009085),
('Mg26', 0.0104025), ('F19', 0.414511),
('U234', 1.060551431), ('U235', 0.0014209),
('U238', 0.198313), ('Cl35', 0.0444628),
('Cl37', 0.0150386), ('Na23', 0.046301),
('F19', 0.0510167), ('U234', 5.65627430),
('U235', 0.00075782), ('U238', 0.105767),
('F19', 0.034011)]
I tried doing:
for n in nu:
for ind, id_wf in enumerate(nu_ew):
if n == id_wf[0]:
del nu_ew[ind]`
print(nu_ew)`
I would just use list comprehension here:
something like
result = [t for t in nu_ew if t[0] not in nu]
For larger lists
nu_as_set = set(nu)
result = [t for t in nu_ew if t[0] not in nu_as_set]
Two points to address.
Don't delete/add an element to a list while iterating over it. Instead, make a new list containing the result. This can be done by a for loop, or by list comprehension.
You don't have to iterate over nu, just use in. If nu is going to be larger, consider using a set, because it takes less time with in operator.
So, either one of the following will work for your second code.
Use for loop.
result = []
for id_wf in nu_ew:
if id_wf[0] in nu:
result.append(id_wf)
nu_ew = result
print(nu_ew)
Use list comprehension.
nu_ew = [id_wf in nu_ew if id_wf[0] in nu]
Making a set out of nu is simple, just add
nu = set(nu)
or
nu_set = set(nu)
(If you want to keep the original list)
beforehand.

Making several wordclouds out of list of dictionaries

I have a list of dictionaries in union_dicts. To give you an idea it's structured as follows
union_dicts = [{'bla' : 6, 'blub': 9}, {'lub': 20, 'pul':12}]
(The actual lists of dicts is many times longer, but this is to give the idea)
For this particular list of dictionaries I want to make a wordcloud. The function that makes a wordcloud is as follows (nothing wrong with this one):
def make_words(words):
return ' '.join([('<font size="%d">%s</font>'%(min(1+words[x]*5/max(words.values()), 5), x)) for x in words])
Now I have written the following code that should give every dictionary back. Return gives only the first dictionary back in the following function below:
def bupol():
for element in union_dicts:
return HTML(make_words(element))
bupol()
I have already tried to simply print it out, but then I simply get ''Ipython display object'' and not the actual display. I do want the display. Yield also doesn't work on this function and for some reason using list = [] along with list.apped() return list instead of returning in the current way also doesn't work. I'm quite clueless as how to properly iterate over this so I get a display of every single dictionary inside union_dicts which is a list of dictionaries.
How about something like this?
def bupol():
result = []
for element in union_dicts:
result.append(HTML(make_words(element)))
return result

Python appending a list to a list and then clearing it

I have this part of code isolated for testing purposes and this question
noTasks = int(input())
noOutput = int(input())
outputClist = []
outputCList = []
for i in range(0, noTasks):
for w in range(0, noOutput):
outputChecked = str(input())
outputClist.append(outputChecked)
outputCList.append(outputClist)
outputClist[:] = []
print(outputCList)
I have this code here, and i get this output
[[], []]
I can't figure out how to get the following output, and i must clear that sublist or i get something completely wrong...
[["test lol", "here can be more stuff"], ["test 2 lol", "here can be more stuff"]]
In Python everything is a object. A list is a object with elements. You only create one object outputclist filling and clearing its contents. In the end, you have one list multiple times in outputCList, and as your last thing is clearing the list, this list is empty.
Instead, you have to create a new list for every task:
noTasks = int(input())
noOutput = int(input())
output = []
for i in range(noTasks):
checks = []
for w in range(noOutput):
checks.append(input())
output.append(checks)
print(output)
Instead of passing the contained elements in outputClist to outputCList (not the greatest naming practice either to just have one capitalization partway through be the only difference in variable names), you are passing a reference to the list itself. To get around this important and useful feature of Python that you don't want to make use of, you can pretty easily just pass a new list containing the elements of outputClist by changing this line
outputCList.append(outputClist)
to
outputCList.append(list(outputClist))
or equivalently, as #jonrsharpe states in his comment
outputCList.append(outputClist[:])

Categories

Resources