How do I use other elements fom one list? - python

I have a list of lists:
data = [['2001', '20', '0', '0', '10', '0', '15', '0'],
['2004', '15', '0', '9.5', '13', '10', '18', '30']]
My work is to use items of sublists in this list of lists:
def FinalMark(studentNum):
if studentNum in data:
I don't know what to do next. Let's say if 2001 is the first item of a sublist, I want to know how to use others items of this sublist.

There are better ways to do it by storing the data as a dictionary. But with what you have, you can loop through data:
def FinalMark(studentNum):
for marks in data:
if marks[0] == studentNum:
return sum([float(i) for i in marks[1:]])
marks[1:] is a slice of marks that skips the first element (the student number).

Related

How do I stop Python treating list items as one item instead of multiple when appending to another list? [duplicate]

This question already has answers here:
What is the difference between Python's list methods append and extend?
(20 answers)
Closed last month.
I have a list called MBN2 thats values are 15 and 13. I'm trying to append it to another list called BoutNumber2, but when I try to do this it treats MBN2 as one list item ['15', '13'] instead of two. When I print the length of MBN2 it says two so I'm not sure why it's doing this. Here is the block of code
for test4 in soup.select('.fight_card_resume'):
MBN2.append(test4.find('td').get_text().replace('Match ', ''))
for test7 in soup.select('.new_table_holder [itemprop="subEvent"] td'):
BoutNumber.append(test7.get_text().strip())
BoutNumber2 = BoutNumber[0::7]
BoutNumber2.append(MBN2)
and this is what I get when I print BoutNumber2 afterwards
['14', '13', '12', '11', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1', '12', '11', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1', ['15', '13']]
How do I get Python to treat the appended 15 and 13 as seperate?
Just this should work:
BoutNumber2 = BoutNumber2 + MBN2
or you could do
BoutNumber2.extend(MBN2)
Both solutions should do the job.

Building chains from nested list

I have a nested list:
[['мама', 'мыть', '10', 'рама'],
['мыть', 'рама', '5', 'долго'],
['мама', 'мыть', '10', 'рама'],
['мыть', 'рама', '3', 'вчера'],
['мыть', 'рама', '10', 'вчера'],
['рама', 'вчера', '1', 'поздно']]
What I need is to build chains where last two non-digital string elements of one list are equal to first two non-digital string elements of another list, for example in:
['Мама', 'мыть', '10', 'рама']
and
['мыть', 'рама', '5', 'долго']
'мыть', 'рама' are a match, so the final output should be:
[['мама', 'мыть', '10', 'рама', '5', 'долго'],
['мама', 'мыть', '10', 'рама', '3', 'вчера'],
['мама', 'мыть' '10', 'рама', '3', 'вчера', '1', 'поздно']]
Digits are kind of probability and should be left as is. I think there should be some kind of iterative search, but I am not sure.
Any help would be appreciated.
1 - Create a dictionary from your list, with the key being the first two words, combined. Something like:
key: 'Мама_мыть' value: ['Мама', 'мыть', '10', 'рама'],
key: 'мыть_рама' value: ['мыть', 'рама', '5', 'долго'],
... etc ...
2 - Iterate over your list, creating a key from the last two non-numeric values in each entry. And look that value up in the dictionary.
3 - When you find a match, create the output.

How to work out an average from items within a dict.?

I am new to python so a simplified explanation would be much appreciated!
As of now I have a dictionary that looks like this:
names = {'Bob Smith': ['5', '6', '7', '5'], 'Fred Jones': ['8', '5', '7', '5', '9'], 'James Jackson': ['5','8','8','6','5']}
I need to do the following:
Take the last three items from each of the entries in the dict. e.g. 6, 7, 5 for bob smith.
Calculate an average based upon those values. e.g. Bob smith would be 6.
List the averages in order from highest to lowest (without the dict keys).
So far I have the following enclosed in an if statement:
if method == 2:
for scores in names.items():
score = scores[-1,-2,-3]
average = sum(int(score)) / float(3)
print(average)
I had a look at this thread too but I am still stuck.
Can anyone give me some pointers?
Scores[-1,-2,-3] does not get the last three elements. It gets the element at the key (-1,-2,-3) in a dictionary, which will raise an error in the case of a list. Scores[-3:] would get the last three elements.
When getting the scores, you need to use names.values() instead of names.items()
The python string-to-integer conversions in the int type constructor are not smart enough to handle lists of strings, only individual strings. Using map(int,score) or int(i) for i in score would fix that.
The variable score is also an extremely poor choice of name for a list of elements.
In Python3.4+, there is a statistics module
>>> names = {'Bob Smith': ['5', '6', '7', '5'], 'Fred Jones': ['8', '5', '7', '5', '9'], 'James Jackson': ['5','8','8','6','5']}
>>> import statistics
>>> sorted((statistics.mean(map(int, x[-3:])) for x in names.values()), reverse=True)
[7.0, 6.333333333333333, 6.0]
names = {'Bob Smith': ['5', '6', '7', '5'], 'Fred Jones': ['8', '5', '7', '5', '9'], 'James Jackson': ['5','8','8','6','5']}
def avg(l):
l = list(map(int,l))
return sum(l[-3:])/3
avgs = []
for each in names.values():
avgs.append(avg(each))
avgs.sort(reverse=True)
print avgs
Output:
[7, 6, 6]

using a for loop to compare lists

The problem at hand is I have a list of lists that I need to iterate through and compare one by one.
def stockcheck():
stock = open("Stock.csv", "r")
reader = csv.reader(stock)
stockList = []
for row in reader:
stockList.append(row)
The output from print(stockList) is:
[['Product', 'Current Stock', 'Reorder Level', 'Target Stock'], ['plain blankets', '5', '10', '50'], ['mugs', '15', '20', '120'], ['100m rope', '60', '15', '70'], ['burner', '90', '20', '100'], ['matches', '52', '10', '60'], ['bucket', '85', '15', '100'], ['spade', '60', '10', '65'], ['wood', '100', '10', '200'], ['sleeping bag', '50', '10', '60'], ['chair', '30', '10', '60']]
I've searched the basics for this but i've had no luck... I'm sure the solution is simple but it's escaping me! Essentially I need to check whether the current stock is less than the re-order level, and if it is save it to a CSV (that part I can do no problem).
for item in stockList:
if stockList[1][1] < stockList[1][2]:
print("do the add to CSV jiggle")
This is as much as I can do but it doesn't iterate through... Any ideas? Thanks in advance!
Iterate through the stockList using list comprehension, maybe and then print out the results
[sl for sl in stockList[1:] if sl[1] < sl[2]]
You will get the following results:
[['mugs', '15', '20', '120']]
In case you were wondering stockList[1:] is to ensure that you ignore the header.
However, you must note that the values are strings that are being compared. Hence, the values are compared char by char. If you want integer comparisons then you must convert the strings to integers, assuming you are absolutely sure that sl[1] and sl[2] will always be integers - just being presented as strings. Just try doing:
[sl for sl in stockList[1:] if int(sl[1]) < int(sl[2])]
The result changes:
[['plain blankets', '5', '10', '50'], ['mugs', '15', '20', '120']]
Use the [1:] to not get the header, and then make the comparation.
for item in stockList[1:]:
if item[1] < item[2]:
print item
print("do the add to CSV jiggle")

How can i sort integers in a list, if they are in a string?

I have a controlled assessment, and need to be able to order scores from a test in numerical and alphabetical order. How do i do this if they are connected to the persons name who completed the quiz. All names are within 1 list, For example ["John, 9"], ["alfie, 6"] etc
any help much appreciated!
If you want to sort a list of strings based on a transformation on each of these strings, you can use the function sorted with the key keyword argument:
>>> l = ['10', '9', '100', '8']
>>> sorted(l)
['10', '100', '8', '9']
>>> sorted(l, key=int)
['8', '9', '10', '100']
>>> def transformation(x):
... return -int(x)
...
>>> sorted(l, key=transformation)
['100', '10', '9', '8']
What the key function does is that the strings are not compared directly, but the values that are returned by the function are.

Categories