How to get specific values from a list in Python - python

So I am getting some data of a spreadsheet using gspread and they all go into a list. But I would like to just get the second, third and fourth value of that list separately.
Is there any way I can do this is python 3?
The lists look like this:
['22-6-2020 15:54:53', '4', '5', '46'],
['22-6-2020 15:54:53', '5', '3', '67'],
['22-6-2020 15:54:53', '1', '7', '5'],
['22-6-2020 15:54:53', '3', '86', '67'],
['22-6-2020 15:54:53', '1', '26', '12']

You can do so using list comprehension
data = [['22-6-2020 15:54:53', '4', '5', '46'],
['22-6-2020 15:54:53', '5', '3', '67'],
['22-6-2020 15:54:53', '1', '7', '5'],
['22-6-2020 15:54:53', '3', '86', '67'],
['22-6-2020 15:54:53', '1', '26', '12']]
l1, l2, l3 = [[d[x] for d in data] for x in range(1,4)]
print(l1, l2, l3)
#prints
['4', '5', '1', '3', '1'] ['5', '3', '7', '86', '26'] ['46', '67', '5', '67', '12']

Related

histogram is not visible using matplotlib and would like to group values in the x axis within intervals

I would like to plot a histogram but the problem is that my histogram is not visible. Here is what my histogram looks like:
I would like to use the following intervals within my axis: [-1,0] ]0,1], ]1,2]]2,4],]4,8],]8,16],]16,32]
Here is the code I am using:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
x = ['0', '1', '2', '3', '4', '5', '6','7', '8', '9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','38','40','41','42','43','44','45','48','50','51','53','54','57','60','64','70','77','93','104','108','147']
y= ['164','189','288','444','311','216','122','111','92','54','45','31','31','30','18','15','15','10','4','15','2','8','6','4','7','5','3','3','1','10','3','3','3','2','4','2','1','1','1','2','2','1','1','1','1','1','2','1','2','2','2','1','1','2','1','1','1','1']
x = [int(i) for i in x]
y = [int(i) for i in y]
plt.bar(x, y)
plt.xlabel('Variable accesses')
plt.ylabel('Number of Variables')
plt.show()
How can I fix this?
You could create lists with the interval labels and the corresponding sums:
import matplotlib.pyplot as plt
x = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20',
'21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '38', '40', '41',
'42', '43', '44', '45', '48', '50', '51', '53', '54', '57', '60', '64', '70', '77', '93', '104', '108', '147']
y = ['164', '189', '288', '444', '311', '216', '122', '111', '92', '54', '45', '31', '31', '30', '18', '15', '15', '10',
'4', '15', '2', '8', '6', '4', '7', '5', '3', '3', '1', '10', '3', '3', '3', '2', '4', '2', '1', '1', '1', '2',
'2', '1', '1', '1', '1', '1', '2', '1', '2', '2', '2', '1', '1', '2', '1', '1', '1', '1']
x = [int(xi) for xi in x]
y = [int(yi) for yi in y]
start = -1
end = 0
intervals = []
values = []
while end < 2 * max(x):
intervals.append(f'$]{start},{end}]$')
values.append(sum([yi for xi, yi in zip(x, y) if start < xi <= end]))
start = end
end = 1 if end == 0 else 2 * end
fig, ax = plt.subplots(figsize=(12, 4))
ax.bar(intervals, values)
ax.set_xlabel('Variable accesses')
ax.set_ylabel('Number of Variables')
ax.margins(x=0.02)
plt.tight_layout()
plt.show()

How to bubble sort a 2D array with python

I have this list that's a summary of a few NHL player stats in 2018. I want to sort them by pts which is the 7th value using bubble. I am aware of the built-in sort function on python but I would rather use bubble sort or even quicksort for that matter. Can anyone help out?
[['A.J. Greer', 'COL', 'LW', '15', '1', '1', '2', '14', '9', '20', '5'], ['Aaron Ekblad', 'FLA', 'D', '82', '13', '24', '37', '47', '180', '114', '88'], ['Adam Clendening', 'CLS', 'D', '4', '0', '0', '0', '0', '3', '1', '3'], ['Adam Cracknell', 'FA', 'C', '2', '0', '0', '0', '0', '3', '6', '0'], ['Adam Erne', 'DET', 'LW', '65', '7', '13', '20', '40', '70', '159', '26'], ['Adam Gaudette', 'VAN', 'C', '56', '5', '7', '12', '18', '55', '48', '15']]
This is what I did so far:
def sortByPoints(stats):
lengthOfstats = len(stats) - 1
for i in range(lengthOfstats):
for j in range(lengthOfstats - i):
if stats[j] < stats[j + 1]:
stats[j], stats[j + 1] = stats[j + 1], stats[j]
return stats
print(sortByPoints(readStatsFromFile()))
Create bubble sort that can sort nested-arrays based upon an index of sub-array
Modification of BubbleSort
def bubbleSort(arr, ind = 6):
"""Bubble sort arr based upon subelement ind (default of index 6)
which is 7th element of sub-array since 0 based indexing"""
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if int(arr[j][ind]) > int(arr[j+1][ind]) :
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
Test
arr = [['A.J. Greer', 'COL', 'LW', '15', '1', '1', '2', '14', '9', '20', '5'], ['Aaron Ekblad', 'FLA', 'D', '82', '13', '24', '37', '47', '180', '114', '88'], ['Adam Clendening', 'CLS', 'D', '4', '0', '0', '0', '0', '3', '1', '3'], ['Adam Cracknell', 'FA', 'C', '2', '0', '0', '0', '0', '3', '6', '0'], ['Adam Erne', 'DET', 'LW', '65', '7', '13', '20', '40', '70', '159', '26'], ['Adam Gaudette', 'VAN', 'C', '56', '5', '7', '12', '18', '55', '48', '15']]
import pprint
print('pre-sorted')
pprint.pprint(arr)
print('sorted')
pprint.pprint(bubbleSort(arr))
Output
pre-sorted
[['A.J. Greer', 'COL', 'LW', '15', '1', '1', '2', '14', '9', '20', '5'],
['Aaron Ekblad', 'FLA', 'D', '82', '13', '24', '37', '47', '180', '114', '88'],
['Adam Clendening', 'CLS', 'D', '4', '0', '0', '0', '0', '3', '1', '3'],
['Adam Cracknell', 'FA', 'C', '2', '0', '0', '0', '0', '3', '6', '0'],
['Adam Erne', 'DET', 'LW', '65', '7', '13', '20', '40', '70', '159', '26'],
['Adam Gaudette', 'VAN', 'C', '56', '5', '7', '12', '18', '55', '48', '15']]
sorted
[['Adam Clendening', 'CLS', 'D', '4', '0', '0', '0', '0', '3', '1', '3'],
['Adam Cracknell', 'FA', 'C', '2', '0', '0', '0', '0', '3', '6', '0'],
['A.J. Greer', 'COL', 'LW', '15', '1', '1', '2', '14', '9', '20', '5'],
['Adam Gaudette', 'VAN', 'C', '56', '5', '7', '12', '18', '55', '48', '15'],
['Adam Erne', 'DET', 'LW', '65', '7', '13', '20', '40', '70', '159', '26'],
['Aaron Ekblad', 'FLA', 'D', '82', '13', '24', '37', '47', '180', '114', '88']]

How to create new lists in python

I want to create new lists from one list. This the example list I am working on:
matrixlist = [['Matrix', '1'], ['1', '4', '6'], ['5', '2', '9'], ['Matrix', '2'], ['2', '6'], ['1', '3'], ['8', '6'], ['Matrix', '3'], ['5', '6', '7', '9'], ['1', '4', '2', '3'], ['8', '7', '3', '5'], ['9', '4', '5', '3'], ['Matrix', '4'], ['7', '8'], ['4', '6'], ['2', '3']]
I split them like this with for loop:
matrix1 = [['1', '4', '6'], ['5', '2', '9']]
matrix2 = [['2', '6'], ['1', '3'], ['8', '6']]
matrix3 = [['5', '6', '7', '9'], ['1', '4', '2', '3'], ['8', '7', '3', '5'], ['9', '4', '5', '3']]
matrix4 = [['7', '8'], ['4', '6'], ['2', '3']]
But I want to give the long list to program and it create lists and append the relevant elements in it. Like matrix 1 elements in matrix1 list.
Edit: I can't use any advanced built-in function. I can only use simple ones (like append, pop, reverse, range) and my functions in code.
You can use itertools.groupby:
from itertools import groupby
matrixlist = [['Matrix', '1'], ['1', '4', '6'], ['5', '2', '9'], ['Matrix', '2'], ['2', '6'], ['1', '3'], ['8', '6'], ['Matrix', '3'], ['5', '6', '7', '9'], ['1', '4', '2', '3'], ['8', '7', '3', '5'], ['9', '4', '5', '3'], ['Matrix', '4'], ['7', '8'], ['4', '6'], ['2', '3']]
result = [list(b) for a, b in groupby(matrixlist, key=lambda x:x[0] == 'Matrix') if not a]
Output:
[[['1', '4', '6'], ['5', '2', '9']],
[['2', '6'], ['1', '3'], ['8', '6']],
[['5', '6', '7', '9'], ['1', '4', '2', '3'], ['8', '7', '3', '5'], ['9', '4', '5', '3']],
[['7', '8'], ['4', '6'], ['2', '3']]]
you can do it using list comprehension like below
indx = [i for i, mat in enumerate(matrixlist )if mat[0]=='Matrix']
matrixes = {matrixlist[i][1]: matrixlist[i+1: j] for i, j in zip(indx, indx[1:])}
# access matrix with its id
matrixes["1"]

Removing all non digits from a list

After reading from a file I have a list of lists contaning not only digits but also other characters, which I would like to get rid of.
I've tried using re.sub function but this doesn't seem to work
import re
Poly_id= [['0', '[4', '8', '18', '20', '5', '0', '4]'], ['1', '[13', '16',
'6', '11', '13]'], ['2', '[3', '1', '10', '9', '2', '15', '3]'], ['3',
'[13', '12', '16', '13]'], ['4', '[13', '11', '17', '14', '7', '13]']]
for x in Poly_id:
[re.sub(r'\W', '', ch) for ch in x]
This doesn't seem to change a thing in this list.
I would like to have a list with only numbers as elements so that I could convert them into integers
I guess technically [4 is non numeric so you can do something like this:
Poly_id = [[char for char in _list if str.isnumeric(char)] for _list in Poly_id]
Output:
['0', '8', '18', '20', '5', '0']
['1', '16', '6', '11']
['2', '1', '10', '9', '2', '15']
['3', '12', '16']
['4', '11', '17', '14', '7']
If you just want to remove the non numeric values and not the complete entry then you can do this:
Poly_id = [[''.join(char for char in substring if str.isnumeric(char)) for substring in _list] for _list in Poly_id]
Output:
['0', '4', '8', '18', '20', '5', '0', '4']
['1', '13', '16', '6', '11', '13']
['2', '3', '1', '10', '9', '2', '15', '3']
['3', '13', '12', '16', '13']
['4', '13', '11', '17', '14', '7', '13']
Here a solution if you want to get rid of the '[' in '[4' but keep the '4':
res = [[re.sub(r'\W', '', st) for st in inlist] for inlist in Poly_id]
res is:
[
['0', '4', '8', '18', '20', '5', '0', '4'],
['1', '13', '16', '6', '11', '13'],
['2', '3', '1', '10', '9', '2', '15', '3'],
['3', '13', '12', '16', '13'],
['4', '13', '11', '17', '14', '7', '13']
]
You can use a module, "itertools"
import itertools
list_of_lists = [[1, 2], [3, 4]]
print(list(itertools.chain(*list_of_lists)))
>>>[1, 2, 3, 4]

Adding counter/index to a list of lists in Python

I have a list of lists of strings:
listBefore = [['4', '5', '1', '1'],
['4', '6', '1', '1'],
['4', '7', '8', '1'],
['1', '2', '1', '1'],
['2', '3', '1', '1'],
['7', '8', '1', '1'],
['7', '9', '1', '1'],
['2', '4', '3', '1']]
and I would like to add a counter/index in the middle of each list so that the list looks like:
listAfter = [['4', '5', '1', '1', '1'],
['4', '6', '2', '1', '1'],
['4', '7', '3', '8', '1'],
['1', '2', '4', '1', '1'],
['2', '3', '5', '1', '1'],
['7', '8', '6', '1', '1'],
['7', '9', '7', '1', '1'],
['2', '4', '8', '3', '1']]
What would be the easiest way to do so? I could probably loop over the lists and add the index, but is there a cleaner way to do so?
Cheers,
Kate
Edit:
The code I wrote works for me:
item = 1
for list in listBefore:
list.insert(2,str(item))
item = item + 1
print listBefore
I was wondering if there is another way to do so more efficiently or in one step.
Iterate over the parent list with enumerate() to get counter (used as i in the below example) along with list element. In the sublist, insert the i at the middle of sublist using list.insert(index, value) method.
Note: The value of counter i.e. i will be of int type, so you have to explicitly type cast it to str as str(i)before inserting. Below is the sample code:
for i, sub_list in enumerate(my_list, 1): # Here my_list is the list mentioned in question as 'listBefore'
sub_list.insert(len(sub_list)/2, str(i))
# Value of 'my_list'
# [['4', '5', '1', '1', '1'],
# ['4', '6', '2', '1', '1'],
# ['4', '7', '3', '8', '1'],
# ['1', '2', '4', '1', '1'],
# ['2', '3', '5', '1', '1'],
# ['7', '8', '6', '1', '1'],
# ['7', '9', '7', '1', '1'],
# ['2', '4', '8', '3', '1']]
You can perform this with a list comprehension
listAfter = [listBefore[i][:len(listBefore[i])/2] + [str(i+1)] + listBefore[i][len(listBefore[i])/2:] for i in range(len(listBefore))]
You should learn about enumerate, it lets you iterate over the list with two iterators - one (str_list in this case) holds the current item in the list, and the other (i`) holds it's index in the list.
for i,str_list in enumerate(listBefore):
listBefore[i] = str_list[:len(str_list)//2] + [str(i+1)] + str_list[len(str_list)//2:]
>>> data = [['4', '5', '1', '1'],
['4', '6', '1', '1'],
['4', '7', '8', '1'],
['1', '2', '1', '1'],
['2', '3', '1', '1'],
['7', '8', '1', '1'],
['7', '9', '1', '1'],
['2', '4', '3', '1']]
>>> print [row[:len(row)//2] + [str(i)] + row[len(row)//2:]
for i, row in enumerate(data, start=1)]
[['4', '5', '1', '1', '1'],
['4', '6', '2', '1', '1'],
['4', '7', '3', '8', '1'],
['1', '2', '4', '1', '1'],
['2', '3', '5', '1', '1'],
['7', '8', '6', '1', '1'],
['7', '9', '7', '1', '1'],
['2', '4', '8', '3', '1']]

Categories

Resources