How to write multi list in list of tuple - python-3.x

In the func function, I performed some processing on the oldlist[] and then saved the result in a buffer[] list. Now I want to save this buffer[]list to be the first one in a list of tuples. After that, a new values in buffer[] must be saved as a second list in tuples and so on.
The output something like this
#list of tuple:
Ltuple=[(1,2,3),(66,53,6),(3,1,5,8,3)]
I do not know how to use list of tuple any advice please?
def func(oldlist):
buffer = []
buffer.append(oldlist[0])
# some processing on the items of oldlist[]
buffer.append(oldlist[index])
print(buffer)
# Now here I need to append the buffer[] in list of tuple to be the
# first list in tuple and in next time the new list insert to be
# the second list in list of tuple
buffer.clear()
oldlist=[]
#Some code to deal with oldlist[] and in each time send some items
# from oldlist[] to func()
func(oldlist)
oldlist.clear()

Can you pass Ltuple to the function?
If not it has to be made global or you need to return the buffer tuple
I have modified the function below to take the list of tuples also.
def func(oldlist, list_of_tuples):
buffer = []
buffer.append(oldlist[0])
# some processing on the items of oldlist[]
buffer.append(oldlist[index])
print(buffer)
# Now here I need to append the buffer[] in list of tuple to be the
# first list in tuple and in next time the new list insert to be
# the second list in list of tuple
list_of_tuples.append(tuple(buffer))
buffer.clear()
oldlist=[]
#Some code to deal with oldlist[] and in each time send some items
# from oldlist[] to func()
list_of_tuples = []
func(oldlist, list_of_tuples)
oldlist.clear()

Related

How do I check if a filter returns no results in Python 3?

I have a filter function that I use to clean certain items out of a list:
def filterOutPatternMatches(objList, matchKey, matchPatterns):
def checkPatterns(obj):
delete_it=True
for pat in matchPatterns:
matchString=obj[matchKey]
if pat.search(matchString):
delete_it=False
break
return delete_it
result = filter(checkPatterns, objects);
return result
It works fine, except that there is no easy way for me to find out if the filter() function has returned an empty iterable.
I want to know if the list is empty, and if so, do one thing. If not, do something else.
There are three ways to approach this:
Convert the filter object to a list, then check if it is empty:
l = list(filterObject)
if (len(l) == 0):
# The filterObject is empty, do the empty thing
The problem is that you have to convert the filterObject iterable to a list, which is potentially a very expensive operation if the iterable is very large.
Use next() to pull the first item off of the filter object iterable. If there is nothing in the list, you will get a StopIteration error, which you have to catch.
You will also need to process the first item outside of the rest, since you can't put it back on the iterable.
try:
firstItem = next(filterObject)
# Do whatever you need to do with the first item in the filterObject iterable
except StopIteration:
# Do whatever you do if there are no filter results
for o in filterObject:
# Now handle the rest of the filter results
Problems with this: you have to handle the first item outside of your for loop, which is annoying. If you want to run some aggregation function on the filterObject iterable, you have to deal with the one item that you pulled off separately. Very un-pythonic.
Iterate over the filterObject as you normally would, but set a flag if it is empty:
filterObject = filter(someFunc, someIterable)
itWasEmpty=true
for x in filterObject:
itWasEmpty=false
# Process the filterObject items
if itWasEmpty:
# Do whatever you do if it's empty.
Cons: You need to process the entire list manually. Can't pass the filter object to an aggregation function.
That's all I can come up with!

random iteration over the items of the list

I want to iterate randomly over some given items in my list
for example:
items = ['rock', 'paper', 'scissors']
for item in items:
print(random.shuffle(items))
I want in each iteration it splits out a random item from my list but everytime it gives 'None'
random.shuffle() shuffles the list in-place and it returns None.
You need to:
import random
items = ['rock', 'paper', 'scissors']
for item in random.sample(items,3): # get list of n=3 random shuffled values no dupes
print(item)
# or
random.shuffle(items) # shuffle in place (might get the same order as well)
for item in items:
print(item)
See differences between:
https://docs.python.org/3.8/library/random.html#random.shuffle (in place)
https://docs.python.org/3.8/library/random.html#random.sample (no dupes)
https://docs.python.org/3.8/library/random.html#random.choices (maybe dupes)

Function to iterate through a nested list and append other lists isn't functioning properly

I am currently trying to write a function to iterate through a nested list and check if one item from the list, 'team', is already in a separate list 'teams'.
If it is not, I want to append a nested list, 'player_values' with a different item from the original nested list that was examined, in the form of a new list in the nested list.
If it is, I want to append the nested list 'player_values' with the item from the original nested list, but I want to add it to the most recent list in the nested list 'player_values' instead of creating a new list.
Currently, my code looks like this :
def teams_and_games(list, player, idx):
teams = []
player_values = []
x = 0
y = -1
for rows in list:
if player == list[x][BD.player_id] and list[x][BD.team] not in teams:
teams.append(list[x][BD.team])
player_values.append([list[x][idx]])
x += 1
y += 1
elif player == list[x][BD.player_id]:
player_values[y].append(list[x][idx])
x += 1
return player_values, teams
However, when I run the code in my main, using
values, teams = teams_and_games(NiceRow, name, BD.games)
print(values)
print(teams)
It only prints empty lists. The fact that it prints empty lists shows that it is returning the correct variables, but I can't figure out why the code in the function is failing to add anything to the lists. I have tried switching the .append with a more simple list += statement, but the result has been the same so far.
Ideally, I would be getting a nested list, containing an amount of lists equal to the number of items added to the other 'teams' list, and the list of teams in the order they were added.
The data I am working with is a nested list pulled from a .csv file, which has been formatted slightly using the .strip() and .split() commands. Each number has been converted to an int, and strings left as they are. The .CSV file it is from has 19 columns and ~80,000 rows, with each column always being either a string or an int.

adding data to a nested list of lists

any help would be appreciated! I'm scraping multiple URLs and iterating over the URLs with a for loop. I'm putting relevant data into individual lists. however, I'm trying to organize my data in a list of lists to compare with other data... that I have't scraped yet. How do I iterate through the list of lists and put data into each element of the list? this doesn't seem that hard... don't know what I'm missing?
def get_info(item_urls)#, count): #count is being passed in, leaving this here for context
for item in item_urls:
#get data and stuff from current URL
data = ["beer", "is", "awesome!", "...", "for", "helping", "with", "my", "depression"]
count = len(data) # counting data for a number, that I should have just made up :)
table = [[] for i in range(0, count)]
for truth in data:
for i in range(0, count):
list('table[{}]'.format(i)).append(truth)
print(truth)
for thing in table[0]:
print(thing)
return "borked"
my fake logic:
for each element in data, append the element to table.
Once I iterate through all the URLs, I would like to return the entire built out table.
myList[i] iterates through a list. myList[i][j] iterates through elements in list of lists. j is the index for element in the inner list.

Python Crash Course exercise 8-11

I am working through the Python Crash Course book by Eric Matthes and I am stuck on 8-11. I don't quite understand how to return the new list and store it in a separate list.
So far I have tried to call the function by making a copy of the list.
def make_great(magicians):
"""This function adds the 'The Great' in front of a magicians name"""
great_magicians = [] #A new list to hold names of new magicians
while magicians: #This while loop runs while the parameter 'magicians' has elements in it
magician = magicians.pop() #Element from magicians parameter held in magician varibale
great_magician = magician + " the Great" #Creating a new element to store great_magician
great_magicians.append(great_magician) #Adding great_magicians to empty list
for great_magician in great_magicians: #Adding elements in great_magician back into magicians
magicians.append(great_magician)
magician_names1 = ['inho','mumbo jumbo','trick shotta','hwolla']
make_great(magician_names1[:])
List are mutable, that is they can be modified. so return the modified list and save it under the variable name of - magician_names1
def make_great(magicians):
"""This function adds the 'The Great' in front of a magicians name"""
great_magicians = [] #A new list to hold names of new magicians
while magicians: #This while loop runs while the parameter 'magicians' has elements in it
magician = magicians.pop() #Element from magicians parameter held in magician varibale
great_magician = magician + " the Great" #Creating a new element to store great_magician
great_magicians.append(great_magician) #Adding great_magicians to empty list
for great_magician in great_magicians: #Adding elements in great_magician back into magicians
magicians.append(great_magician)
return magicians
magician_names1 = ['inho','mumbo jumbo','trick shotta','hwolla']
magician_names1 = make_great(magician_names1[:])
print(magician_names1)
Your current function modifies the list you pass it in place. That means if you call make_great(magician_names1), it will modify the names in your main list and you won't have access to the original values any more.
If you want to make the changes in a new list, there are two general approaches you can take. The first is to change the function so that it creates and returns a new list and does not modify the list you passed in to it. That's pretty easy:
def make_great(magicians):
return [magician + " the Great" for magician in magicians]
# or:
# results = []
# for magician in magicians:
# results.append(magician + " the Great")
# return results
When you call it, you can assign the returned list to a new variable, and the old list will remain the same: great_names = make_great(magician_names1)
The other option is to leave your current function alone, as you might sometimes want to do the modifications in place. In the cases you don't want that, you can first make a copy, then modify the copy in place:
great_names = magician_names1[:] # make a copy and give it a name
make_great(great_names) # then modify the copied list in place
I'll note that while your current code does work for the in place modification, it's a lot more complicated than it needs to be (it also reverses the order the names appear in the list, which may be an undesireable side effect). You can write a much simpler version using the enumerate builtin function to get the index of a name as you iterate over the list it was contained in:
def make_great(magicians):
for i, name in enumerate(magicians):
magicians[i] = name + " the Great"

Resources