I would like to append losowanie1[0] when x = 0 to group1 and so on ( losowanie1[0] when x = 1 to group2...). The same with losowanie2[0], but it comes form other List.
import random
List1 = ['AAAA','BBBBB','CCCCC','DDDD','EEEE']
List2 = ['FFFF','GGGG','HHHH','IIIII','JJJJJ']
Gruop1 = []
Group2 = []
for x in range (len(List1)):
losowanie1 = random.sample(List1,1)
losowanie2 = random.sample(List2,1)
# Here i would like to append losowanie1[0] when x = 0 to group1 and so on ( losowanie1[0] when x = 1 to group2...)
List1.remove(losowanie1[0])
I tried:
('Group' + str(x+1)).append(losowanie1[0])
but obviously i cannot append into string.
I can do it without loop but wanted to make my code more professional. Thanks for any help.
You can make a dictionary with keys (as 'Group' + str(x+1)').
And then add a value to the list!
import random
List1 = ['AAAA','BBBBB','CCCCC','DDDD','EEEE']
base_name = "Group"
my_dic = dict()
for x in range(len(List1)):
my_dic[base_name + str(x +1)] = []
for x in range (len(List1)):
losowanie1 = random.sample(List1,1)
my_dic[base_name + str(x +1)].append(losowanie1[0])
List1.remove(losowanie1[0])
print(my_dic)
Result
{'Group3': ['DDDD'], 'Group4': ['BBBBB'], 'Group1': ['EEEE'], 'Group2': ['CCCCC'], 'Group5': ['AAAA']}
Related
I am trying to make a program where I have a list my_list_1 = [1,2,3,...] and a second list `my_list_2 = [1,2,3,...] and len(my_list_1) < len(my_list_2). I want to iterate through the lists like this:
my_list_1 = [1,2,3]
my_list_2 = [5,6,7,8,9]
result = []
for i in range(len(my_list_2)):
result.append(my_list_1[i] + my_list_2[i])
# i == 0: 1 + 5 = 6
# i == 1: 2 + 6 = 8
# i == 2: 3 + 7 = 10
# i == 3: 1 + 8 = 9
# i == 4: 2 + 9 = 11
""" what I want to happen is when i > len(my_list_1), instead of giving a index out of range
error, I want the loop to start at the beginning if the smaller list"""
I tried something like this:
for i in range(len(my_list_2)):
if i % (len(my_list_1) - 1) == 0 or i == 0:
x = 0
else:
x+=1
result.append(my_list_1[x] + my_list_2[i])
or
for i in range(len(my_list_2)):
if x == (len(my_list_1) - 1) or i == 0:
x = 0
else:
x += 1
result.append(my_list_1[x] + my_list_2[i])
this works but I am looking for something a bit more elegant and possibibly even making a copy of my_list_1 and extend it to the length of my_list_2 so that it would look like this:
>>> my_list_1 = [1,2,3]
>>> my_list_2 = [5,6,7,8,9]
>>> extend_list(my_list_1, len(my_list_2))
[1,2,3,1,2]
You can also use itertools.cycle to create a cyclical list iterator, and use zip for the iterator and the other list.
from itertools import cycle
my_list_1 = [1,2,3]
my_list_2 = [5,6,7,8,9]
# I use list comprehension here
result = [ a + b for a, b in zip(cycle(my_list_1), my_list_2) ]
print(result)
# [6, 8, 10, 9, 11]
You just need modulo for the first index:
for i in range(len(my_list_2)):
x = i % len(my_list_1)
result.append(my_list_1[x] + my_list_2[i])
I have a text file that has 6 lines of numbers:
1,35,1,0,3,1,1.09,5,5,1,0
0,22,1,0,6,4,1.15,5,6,2,0
2,35,1,1,0,1,1.14,6,2,3,0
0,38,1,0,4,3,1.09,3,1,1,0
2,37,1,0,3,3,1.13,4,3,1,0
The function that needs to be printed out is D = (X,y)
X for example using the first line would equal:[0,27,0,1,7,2,1.09,6,5,3]
y for example using the first line would equal: [0] (the last number of that line
I am trying use the values of X and y and make it into this form:
D = (X,y)
How do I do this?
This is what I did which gave me the X and y values
y_list = []
x_list = []
for W in range(0,100):
X = f.readline()
y = X.split(",")
#print(y)
y_list.append(y[10][0])
z_list = []
for Z in range(0,10):
z_list.append(y[Z])
x_list.append(z_list)
print (y_list)
print (x_list)
f.close()
How do I combine both the X and y values properly where it matches D = (X,y)?
For example using the first line
D = ([0,27,0,1,7,2,1.09,6,5,3] , [0])
fo = open('value.txt',"r")
D = []
for l in fo.read().split('\n'):
values = l.split(',')
D.append(values[:-1])
D.append([values[-1]])
print(tuple(D))
The loop goes through list of numbers. I need to use map to accumulate the sum of all element[0] in another list's element[0] , sum of all element[1] in element[1].
result_list = []
sub1 = sub2 = sub3 = 0 #these 3 should be only indexes 0,1,2 of list above
for item in r:
l = item.split(';') # originally l = '34;56;78'
q = list(map(float,l)) # q is the list of 3 elements
#instead of code below I want to have smth like
# result_list = list(map( sum( q(item), result_list)
sub1 += q[0]
sub2 += q[1]
sub3 += q[2]
Input:
l = [['1;2;3'], ['10;20;30'], ['12;34;56']]
result_list must aggregate the sum of all element[0] in each list to result_list[0].
Output
result_list[0] = 1+ 10 + 12
result_list[1] = 2 + 20 + 34
result_list[2] = 3 + 30 + 56
r is this, I omit names and calculate average of each 'column'.
Bawerman;55;79;50
Baldwin;83;62;72
Owen;94;86;65
Watson;92;79;100
Clifford;33;99;47
Murphy;94;87;53
Shorter;83;61;61
Bishop;27;89;41
This is one approach.
Ex:
l = [["1;2;3"], ["10;20;30"], ["12;34;56"]]
result_list = []
l = [list(map(float, j.split(";"))) for i in l for j in i]
for i in zip(*l):
result_list.append(sum(i))
print(result_list)
Output:
[23.0, 56.0, 89.0]
You could do something like this, assuming each element of l is a list of one string:
l = [['1;2;3'], ['10;20;30'], ['12;34;56']]
numbers = (map(float, e.split(';')) for e, in l)
result = [sum(n) for n in zip(*numbers)]
print(result)
Output
[23.0, 56.0, 89.0]
A oneliner can do the job:
If you need first to parse the strings with the numbers:
l = [[int(i) for i in e[0].split(';')] for e in l]
And after that, just:
result = map(sum, zip(*l))
csv.reader + zip + statistics.mean
I omit names and calculate average of each 'column'
You don't need to construct a large list of lists from your data. You can use an iterator and use sequence unpacking with zip. To calculate the mean, you can use statistics.mean:
from io import StringIO
from statistics import mean
import csv
x = StringIO("""Bawerman;55;79;50
Baldwin;83;62;72
Owen;94;86;65
Watson;92;79;100
Clifford;33;99;47
Murphy;94;87;53
Shorter;83;61;61
Bishop;27;89;41""")
# replace x with open('file.csv', 'r')
with x as fin:
reader = csv.reader(x, delimiter=';')
zipper = zip(*reader)
next(zipper) # ignore labels
res = [mean(map(float, x)) for x in zipper]
print(res)
# [70.125, 80.25, 61.125]
If n = 4, m = 3, I have to select 4 elements (basically n elements) from a list from start and end. From below example lists are [17,12,10,2] and [2,11,20,8].
Then between these two lists I have to select the highest value element and after this the element has to be deleted from the original list.
The above step has to be performed m times and take the summation of the highest value elements.
A = [17,12,10,2,7,2,11,20,8], n = 4, m = 3
O/P: 20+17+12=49
I have written the following code. However, the code performance is not good and giving time out for larger list. Could you please help?
A = [17,12,10,2,7,2,11,20,8]
m = 3
n = 4
scoreSum = 0
count = 0
firstGrp = []
lastGrp = []
while(count<m):
firstGrp = A[:n]
lastGrp = A[-n:]
maxScore = max(max(firstGrp), max(lastGrp))
scoreSum = scoreSum + maxScore
if(maxScore in firstGrp):
A.remove(maxScore)
else:
ai = len(score) - 1 - score[::-1].index(maxScore)
A.pop(ai)
count = count + 1
firstGrp.clear()
lastGrp.clear()
print(scoreSum )
I would like to do that this way, you can generalize it later:
a = [17,12,10,2,7,2,11,20,8]
a.sort(reverse=True)
sums=0
for i in range(3):
sums +=a[i]
print(sums)
If you are concerned about performance, you should use specific libraries like numpy. This will be much faster !
A = [17,12,10,2,7,11,20,8]
n = 4
m = 3
score = 0
for _ in range(m):
sublist = A[:n] + A[-n:]
subidx = [x for x in range(n)] + [x for x in range(len(A) - n, len(A))]
sub = zip(sublist, subidx)
maxval = max(sub, key=lambda x: x[0])
score += maxval[0]
del A[maxval[1]]
print(score)
Your method uses a lot of max() calls. Combining the slices of the front and back lists allows you to reduce the amounts of those max() searches to one pass and then a second pass to find the index at which it occurs for removal from the list.
I have a problem I can't seem to get right.
I have 2 numbers, A & B. I need to make a list of A rows with B columns, and have them print out 'R0CO', 'R0C1', etc.
Code:
import sys
A= int(sys.argv[1])
B= int(sys.argv[2])
newlist = []
row = A
col = B
for x in range (0, row):
newlist.append(['R0C' + str(x)])
for y in range(0, col):
newlist[x].append('R1C' + str(y))
print(newlist)
This is not working. The following is the output I get and the expected output:
Program Output
Program Failed for Input: 2 3
Expected Output:
[['R0C0', 'R0C1', 'R0C2'], ['R1C0', 'R1C1', 'R1C2']]
Your Program Output:
[['R0C0', 'R1C0', 'R1C1', 'R1C2'], ['R0C1', 'R1C0', 'R1C1', 'R1C2']]
Your output was incorrect. Try again
You are first adding R0Cx and then R1Cxy. You need to add RxCy. So try:
newlist = []
row = A
col = B
for x in range (0, row):
newlist.append([])
for y in range(0, col):
newlist[x].append('R' + str(x) + 'C' + str(y))
print(newlist)
You have to fill columns in a row while still in that row:
rows = []
row = 2
col = 3
for x in range(0, row):
columns = []
for y in range(0, col):
columns.append('R' + str(x) + 'C' + str(y))
rows.append(columns)
print(rows)
will print:
[['R0C0', 'R0C1', 'R0C2'], ['R1C0', 'R1C1', 'R1C2']]
Try changing your range commands as shown:
for x in range (row):
for y in range(col):
In fact, you have a second issue that you are not modifying the text properly:
newlist = []
row = A
col = B
for x in range (row):
sublist = []
for y in range(col):
sublist.append('R{}C{}'.format(x, y))
newlist.append(sublist)