Define function that reads from Lists of lists - python-3.x

Heres a quick example:-
setup = [['dog','red','big','ears'],
['cat','blue','small','tail']]
def do_it(dummy_parameter):
if do_it [0][0] == 'dog':
print 'dog'
elif do_it [0][0] == 'cat'
print 'cat'
do_it(setup)
Basically looking to go through a list of up to four lists, make an action depending on each of the list contents.. It a bit vague but any assistance would be appreciated! :)
Getting the error
TypeError: 'function' object has no attribute '__getitem__'

Here is an example how to get all the values from a list and list of list :)
with recursion :)
test = [['a', 'b', 'c'],['d', 'e'], 'f']
def separate(item):
try:
for i in item:
if type(i) == list:
separate(i)
else:
print(i)
except IndexError:
pass
separate(test)

Related

Python list comprehension ignore None results?

I have the following toy example function and list comprehension:
def foo(lst):
if lst:
return lst[0] + lst[1]
[foo(l) for l in [[], [1,2], [1,4]]]
The result is:
[None, 3, 4]
How can I avoid the Nones, I would like to avoid calling if foo(l) is not None inside the list comp.
Please advise.
If you want to avoid calling the function more than once, you can make a generator that yields based on the result of the function. It's a little more code, but avoids making a list with a bunch of None values which have to be filtered later, and also avoids calling the function twice in the list comprehension:
def expensive_function(lst):
# sometimes returns None...hard to know when without calling
if lst:
return lst[0] + lst[1]
def gen_results(l):
for a in l:
res = expensive_function(a)
if res:
yield res
inp = [[], [1,2], [1,4]]
list(gen_results(inp))
# [3, 5]
Also, since generators are lazy, you don't need to make a list if you don't need a list.

AttributeError: 'tuple' object has no attribute 'get' in Python 3

I have two lists. one of candidates and one of votes received. I want to sort them descending by votes received. Zipping works fine. When I print the type of the resultant list it comes back as class 'list'. Next I sort and, bam!, get an AttributeError: 'tuple' object has no attribute get. I don't know how to fix this and would appreciate guidance.
for i in range(len(uniquecandidate)):
result = zip(uniquecandidate, votes) # zips two lists together
result_list = list(result)
print(type(result_list)) # returns <class 'list'>
result_list.sort(key=lambda x: x.get('votes'), reverse=True) #sort by vote number
print(result_list, end='\n\n')
zip returns a list of tuples; you can sort them by accessing the elements with their index:
result_list.sort(key=lambda x: x[1], reverse=True)
if you like to be more explicit, you can use collections.namedtuple, and access the element via dot notation on the attribute name:
from collections import namedtuple
Poll = namedtuple('Poll', ['candidate', 'numvotes'])
uniquecandidate = ['a', 'b', 'c', 'd']
votes = [3, 4, 7, 1]
poll_results = list(map(Poll, uniquecandidate, votes))
poll_results.sort(key=lambda x: x.numvotes, reverse=True)
print(poll_results)
or with typing.NamedTuple:
from typing import NamedTuple
class Poll(NamedTuple):
candidate: str
numvotes: int
uniquecandidate = ['a', 'b', 'c', 'd']
votes = [3, 4, 7, 1]
poll_results = list(map(Poll, uniquecandidate, votes))
poll_results.sort(key=lambda x: x.numvotes, reverse=True)
print(poll_results)
out:
[Poll(candidate='c', numvotes=7), Poll(candidate='b', numvotes=4), Poll(candidate='a', numvotes=3), Poll(candidate='d', numvotes=1)]
Because your candidates and votes are stored in a tuple objects, the get() method won't work on them like it would on a dictionary. I recommend switching from
x.get('votes')
to this:
x[1]
This will get index 1 of each tuple (which in your case is the vote count).

Python check variable against multiple lists

So I have 3 lists of data, I need to test if any of the data I get from the json response is in any of the lists, I'm probably being stupid about it but I'm trying to learn and can't seem to get it to work right.
list1 = ['a', 'b', 'c']
list2 = ['a1', 'b1', 'c1']
list2 = ['a2', 'b2', 'c2']
#block of code...
#block of code...
content = json.loads(response.read().decode('utf8'))
data = content
for x in data:
#if x['name'] in list1: #This works fine the line below does not.
if x['name'] in (list1, list2, list3):
print("something")
I suggest something simple and straight-forward:
if (x['name'] in list1 or
x['name'] in list2 or
x['name'] in list3):
...
As a pythinc way for such tasks you can use any for simulating the OR operand and all for and operand.
So her you can use a generator expression within any() :
if any(x['name'] in i for i in (list1, list2, list3))
What about concatenating the lists?
if x['name'] in [list1 + list2 + list3]:

Split strings from integers from a text file

This is the code part of viewing a text file with a list of highscores and putting them into a list. i need to then split the string and integers.
OutList = input("Which class score would you like to view? ").upper()
if OutList == 'A':
List = open("classA.txt").readlines()
print (List)
elif OutList == 'B':
List = open("classB.txt").readlines()
print (List)
elif OutList == 'C':
List = open("classC.txt").readlines()
print (List)
This code currently prints this:
['Bobby 6\n', 'Thomas 4\n']
I need to know how to separate these and get rid of the '\n' to just have the name and score printed out.
Use rstrip()
Here is your modified program:
OutList = input("Which class score would you like to view? ").upper()
if OutList == 'A':
List = open("classA.txt").readlines()
print (List)
elif OutList == 'B':
List = open("classB.txt").readlines()
print (List)
elif OutList == 'C':
List = open("classC.txt").readlines()
for item in List:
print(item.rstrip())
Output:
Which class score would you like to view? A
['Bobby 6\n', 'Thomas 4\n']
Bobby 6
Thomas 4
You can read more on rstrip function here.

recursively add to python dictionary from tuple

I'm attempting to take the tuple ('a', 'b', 'c') and create a layered dictionary like this:
{'a': {'b': {'c': {}}}}. I'm using recursion to do this. When I print out the dictionary after each stage of my script (many prints simply for debugging purposes) it shows that the dictionary is being created correctly, but then it is taken apart and left incorrect. The dictionary I'm left with is {'c': {}}. I must be doing something improper with the recursion part. Any help will be much appreciate. Here is my code:
def incr_dict(dct, tpl):
if len(tpl) == 0:
dct = dct
print(dct)
print('1')
else:
dct = {tpl[-1]:dct}
print(dct)
print('2')
incr_dict(dct, tpl[0:-1])
print(dct)
print('3')
return dct
dct = {}
tpl = ('a', 'b', 'c')
dct=incr_dict(dct, tpl)
print(dct)
print('4')
You're ALMOST there!! Change the incr_dict(dct, tpl[0:-1]) line to read return incr_dict(dct, tpl[0:-1]). I believe that will fix the problem.
When using recursion, it is important to return the recursive call -- otherwise the 'higher levels' of the recursion can't make use of the new information. By returning the recursion, the execution will continue to recurse until the terminating condition is met, and then the computed values will begin to be returned up the chain until they are finally returned from the first invocation of the function.
The final code should look as follows:
def incr_dict(dct, tpl):
if len(tpl) == 0:
dct = dct
else:
dct = {tpl[-1]:dct}
return incr_dict(dct, tpl[0:-1])
return dct
dct = {}
tpl = ('a', 'b', 'c')
dct=incr_dict(dct, tpl)
print(dct)
I removed some of the debugging statements for clarity.

Resources