I want to create an array with the following structure when printed:
1: (10,20),
2: (20,30),
3: (30,40),
4: (40,50),
and so on...
Really new to python so anything helps! Using python 3.
you can simply do by python range function range(start, end, stepsize)
final_lst = []
for i in range(10, 200, 10):
final_lst.append([i, i+10])
print(final_lst)
output
[[10, 20], [20, 30], [30, 40], [40, 50], [50, 60], [60, 70], [70, 80], [80, 90], [90, 100], [100, 110], [110, 120], [120, 130], [130, 140], [140, 150], [150, 160], [160, 170], [170, 180], [180, 190], [190, 200]]
::edit::
for i in range(1, 10):
print('%s: (%s,%s),'%(i, i*10, (i+1)*10))
output
1: (10,20),
2: (20,30),
3: (30,40),
4: (40,50),
5: (50,60),
6: (60,70),
7: (70,80),
8: (80,90),
9: (90,100),
take two variables cnt1 and cnt2
import numpy as np
myList = []
cnt1=1
cnt2=2
for i in range(n): #n is desired length
myList.append([10*cnt1,10*cnt2])
cnt1+=1
cnt2+=1
myArray = np.array(myList)
You can write a function that uses range to get a range of values and a list comprehension (basically an inline for-loop) to generate a list of tuples. Something like this:
def get_repeated_list(max_n):
values = range(10, max_n, 10)
return [(i, i+10) for i in values]
Example usage:
>>> get_repeated_list(50)
[(10, 20), (20, 30), (30, 40), (40, 50)]
Looks like what you want to do is is transform a list into another list of previous/next elements.
listA = [ 10 * i for i in range( N ) ]
listB = [ (listA[ i ], listA[ i + 1 ]) for i in range( len( listA ) - 1 ) ];
Let l be your list. It doesn't matter what is in it. Use zip to make a new list, with wanted feature. zip, matches elements of two list together. if you zip a list with itself, you'll have a new list that each element in first list is repeated twice in it.
l = [1, 2, 5, 11, 12]
for element in zip(l, l):
print(element)
output:
(1, 1)
(2, 2)
(5, 5)
(11, 11)
(12, 12)
Related
My code combines values from two matrices and lists them side by side. T works as I need properly.
We are trying to remove the field where 2 identical values are located. This can be better seen in the example below
my code
import os
import numpy as np
import sys
b=np.array([[13,14,15],
[22,23,24],
[31,32,33]])
#print(b)
d=np.array([100,200,300,400,500])
b[-1,:] = d[:b.shape[1]] # last row
b[:-1,-1] = d[b.shape[1]:]
val1 = np.hstack(b[::-1])
val2 = np.hstack([d[i:i+b.shape[1]] for i in range(b.shape[0])])
res = zip(val1, val2)
for i, j in res:
l=[i, j]
print(l)
my output
[100, 100]
[200, 200]
[300, 300]
[22, 200]
[23, 300]
[500, 400]
[13, 300]
[14, 400]
[400, 500]
My code combines values from two matrices and lists them side by side. T works as I need properly.
We are trying to remove the field where 2 identical values are located. This can be better seen in the example below
I would need to remove matrices in my output that contain the same numbers. As you can see in the output below
The matrices do not always have to be the same and do not have to match the same iterations
required output
[22, 200]
[23, 300]
[500, 400]
[13, 300]
[14, 400]
[400, 500]
Find where the values are different and only concatenate those values.
>>> # using val1 and val2 from the question
>>> mask = np.where(val1!=val2)
>>> mask
(array([3, 4, 5, 6, 7, 8], dtype=int64),)
>>> np.vstack((val1[mask],val2[mask]))
array([[ 22, 23, 500, 13, 14, 400],
[200, 300, 400, 300, 400, 500]])
>>> np.vstack((val1[mask],val2[mask])).T
array([[ 22, 200],
[ 23, 300],
[500, 400],
[ 13, 300],
[ 14, 400],
[400, 500]])
>>>
It is as simple as comparing the two arrays and using the result as a boolean index:
np.stack([val1, val2], axis=1)[val1 != val2]
I got the following list that contains 4 tuples with the scores of each player over 7 games:
players_score = [ ('Joe', 100, 34, 38, 90, 67, 3, 10),
('Bob', 90, 38, 4, 100, 60, 4, 11),
('May', 80, 36, 40, 91, 70, 2, 12),
('Anna', 95, 32, 36, 92, 68, 8, 13) ]
Since I'm trying to learn more about dictionaries, I asked how I could convert the above to a dictionary. I got the following:
# convert player's scores to dictionary
games = {}
for (player_name, *scores) in players_score:
for game_no, score in enumerate(scores, 1):
games.setdefault(game_no, {}).setdefault(player_name, {})
games[game_no][player_name] = score
# the dictionary "games" will look like:
# {1: {'Anna': 95, 'Bob': 90, 'Joe': 100, 'May': 80},
# 2: {'Anna': 32, 'Bob': 38, 'Joe': 34, 'May': 36},
# 3: {'Anna': 36, 'Bob': 4, 'Joe': 38, 'May': 40},
# 4: {'Anna': 92, 'Bob': 100, 'Joe': 90, 'May': 91},
# 5: {'Anna': 68, 'Bob': 60, 'Joe': 67, 'May': 70},
# 6: {'Anna': 8, 'Bob': 4, 'Joe': 3, 'May': 2},
# 7: {'Anna': 13, 'Bob': 11, 'Joe': 10, 'May': 12}}
Now I'm trying out different ways to rank each player's score of each game and then add up those scores to return something like this:
{'Anna': 23, 'May': 18, 'Bob': 16, 'Joe': 15}
The score above is generated when the sum of the ranking of each game is returned. I let the best player, with the highest score of each game earn 4 points, the second one 3, etc.
Of course, it isn't very hard to just sort the outcomes of game 1 like this:
score_list = []
for p in players_score:
score_list.append(p[1])
score_list.sort(reverse=True)
print(score_list)
Returns: [100, 95, 90, 80]
Would it be any good to search in the list/dictionary for these values a then add the points (4/3/2/1) to the name and finally sum them up?
Try this :
from itertools import zip_longest as zilo
tt = list(sorted(i, reverse=True) for i in zilo(*[v for _, *v in players_score]))
# tt = [[100, 95, 90, 80], [38, 36, 34, 32], [40, 38, 36, 4], [100, 92, 91, 90], [70, 68, 67, 60], [8, 4, 3, 2], [13, 12, 11, 10]]
score_dict = {k : sum(4-j.index(i) for i,j in zip(v, tt)) for k, *v in players_score}
Output :
{'Joe': 15, 'Bob': 17, 'May': 18, 'Anna': 20}
Explanation :
First of all, we get the scores of each players for a game in a tuple with zip_longest from itertools with this :
zipped = list(zilo(*[v for _, *v in players_score]))
Now, zipped is :
[(100, 90, 80, 95), (34, 38, 36, 32), (38, 4, 40, 36), (90, 100, 91, 92), (67, 60, 70, 68), (3, 4, 2, 8), (10, 11, 12, 13)]
Check first item (tuple) is the score of four players for the first game and so on. Now we sort each tuple, in the descending order to this :
tt = list(sorted(i, reverse=True) for i in zipped)
So, tt now becomes :
[[100, 95, 90, 80], [38, 36, 34, 32], [40, 38, 36, 4], [100, 92, 91, 90], [70, 68, 67, 60], [8, 4, 3, 2], [13, 12, 11, 10]]
Now, we need to assign scores for each player. We can break down the one-liner dict-comprehension like this :
score_dict = {}
for k, *v in players_score:
tmp = []
for i,j in zip(v, tt):
tmp.append(4-j.index(i)) #Change your score assigning logic here [5,3,1,0] in stead of [4,3,2,1]
#print(tmp) #Check here for scores in each game for a player
tot_score = sum(tmp)
score_dict[k] = tot_score
#print(score_dict)
We iterate over the players_score, we take the first item of each tuple k in it as player name, the rest as another tuple v (the scores of one player in all games), we then zip this tuple v and previous tt, to assign values for rank in each particular game. Scores assigned are 4-the_sorted_one_game_scores_tuple.index(particular_players_score_in_that_game) and all these scores are being appended to a temporary list for each players. After we get the scores for all the games, we sum them up and assign this summation value tot_score as the value to the key k for the score_dict dictionary.
Update :
You can use 5-2*j.index(i) if 5-2*j.index(i) > 0 else 0 in place of 4-j.index(i). Please note that for that case you must have less than 5 games as more than 5 games would assign the last guy and the second last guy both zero. If you want to generalize this logic to assign 0,1,3,5,7,9,... for more number of persons; then you have use a function 2*x-1 if 2*x-1 > 0 else 0 to generate this number sequence. in that case, change inside the second for loop, where we are appending the scores in a temporary list, like this :
# To get 0,1,3,5,7,9,... type score
score_func = lambda x: 2*x-1 if 2*x-1>0 else 0
score_dict = {}
for k, *v in players_score:
tmp = []
for i,j in zip(v, tt):
tmp.append(score_func(j.index(i)))
tot_score = sum(tmp)
score_dict[k] = tot_score
print(score_dict)
I have two lists like this:
list_1 = [100,100,50,40,40,10,20]
list_2 = [5,25,50,120]
I want to take all the elements from list_2 and add it to the end of list_1, also making it a nested list. The output should be like this:
[[100,100,50,40,40,10,20,5],[100,100,50,40,40,10,20,25],[100,100,50,40,40,10,20,50],[100,100,50,40,40,10,20,5,120]]
Is there any possible way of doing this in Python3?
just create a list of lists with list_1 added to a single element list made of each element of list_2:
list_1 = [100,100,50,40,40,10,20]
list_2 = [5,25,50,120]
list_3 = [list_1+[x] for x in list_2]
print(list_3)
result:
[[100, 100, 50, 40, 40, 10, 20, 5], [100, 100, 50, 40, 40, 10, 20, 25], [100, 100, 50, 40, 40, 10, 20, 50], [100, 100, 50, 40, 40, 10, 20, 120]]
Given an array of array A defined as
A = [[1, 2, 3, 4], [10, 20, 30, 40], [100, 200, 300, 400]],
if print function is called
for i in range(0,3):
print A[i]
the following is the output
[1, 2, 3, 4]
[10, 20, 30, 40]
[100, 200, 300, 400].
How can I get a "prettier" output like this:
[ 1, 2, 3, 4]
[ 10, 20, 30, 40]
[100, 200, 300, 400]
???
Thank you
All you need to know is the maximum number of digits that there could be. If the number of digits is three as in your example, do this:
for i in A:
print(", ".join([str(l).rjust(3) for l in i]))
Using str(i).rjust(3) puts i right-justified in a field of width 3 where the extra characters are spaces. You could make them zeros with str(i).zfill(3), or you could make them anything you want with str(i).rjust(3, "&") for example.
Output:
1, 2, 3, 4
10, 20, 30, 40
100, 200, 300, 400
Of course, to make it applicable for more situations, you could use len(str(max(map(max, A)))) instead of hardcoding the 3.
This code will more dynamic. This will find the maximum number's length and rjust by max_len.
A = [[1, 2, 3, 4], [10, 20, 30, 40], [11100, 20033, 300, 400]]
max_len = len(str(max( max(i) for i in A)))
for i in A:
print(", ".join([str(l).rjust(max_len) for l in i]))
Why not using a numpy array for this ?
import numpy as np
print np.array(A)
[[ 1 2 3 4]
[ 10 20 30 40]
[100 200 300 400]]
You can't have those spaces in there if the record is an integer, but this code seems to split up the array nicely.
A = [1999999, 2, 3, 47678], [10, 20, 30, 40], [100, 200, 300, 400]
MaxLength=0
for i in range(0,3):
for x in A[i]:
MaxLength =len(str(x)) if MaxLength<len(str(x)) else MaxLength
for i in range(0,3):
for x in range(0,len(A[i])):
Length=MaxLength-len(str(A[i][x]))
print((" "*Length)+str(A[i][x]),end="|")
print()
If you do want, you can call this up in a definition, just do this:
def TableFormat(A):
MaxLength=0
for i in range(0,3):
for x in A[i]:
MaxLength =len(str(x)) if MaxLength<len(str(x)) else MaxLength
for i in range(0,3):
for x in range(0,len(A[i])):
Length=MaxLength-len(str(A[i][x]))
print((" "*Length)+str(A[i][x]),end="|")
print()
Then you can print the table neatly by doing TableFormat(A) with A as the array. The end="|" can be swapped for anything you want to divide the records with
Easiest way is to use two for loops
for list in A:
for element in list:
print element, '\t',
print '\n'
Try this.
I have a list of ints
list = [25, 50, 70, 32, 10, 20, 50, 40, 30]
And I would like to sum up the ints (from left to right) if their sum is smaller than 99. Lets say I write this output to a list, than this list should look like this:
#75 because 25+50 = 70. 25+50+70 would be > 99
new_list = [75, 70, 62, 90, 30]
#70 because 70+32 > 99
#62 because 32+10+20 = 62. 32+10+20+50 would be > 99
But that is not all. I want to save the ints the sum was made from as well. So what I actually want to have is a data structure that looks like this:
list0 = [ [(25,50),75], [(70),70], [(32, 10, 20),62], [(50, 40),90], [(30),30] ]
How can I do this?
Use a separate list to track your numbers:
results = []
result = []
for num in inputlist:
if sum(result) + num < 100:
result.append(num)
else:
results.append([tuple(result), sum(result)])
result = [num]
if result:
results.append([tuple(result), sum(result)])
For your sample input, this produces:
[[(25, 50), 75], [(70,), 70], [(32, 10, 20), 62], [(50, 40), 90], [(30,), 30]]
You can use iterator fo this:
l = [25, 50, 70, 32, 10, 20, 50, 40, 30]
def sum_iter(lst):
s = 0
t = tuple()
for i in lst:
if s + i <= 99:
s += i
t += (i,)
else:
yield t, s
s = i
t = (i,)
else:
yield t, s
res = [[t, s] for t, s in sum_iter(l)]
On your data result is:
[[(25, 50), 75], [(70,), 70], [(32, 10, 20), 62], [(50, 40), 90], [(30,), 30]]