I have a list of lists
check = [['KH8X070.jpeg', 'ZDO9A8O.jpeg', 'ZW25RD8.jpeg', '6ZLXW92.jpeg', 'HVLA5UT.jpeg', 'A4UDC12.jpeg', '2X5KO9A.jpeg', '5HZR4VV.jpeg', '24FWS4S.jpeg'], ['Z2QC6PW.jpeg', 'EHMK14E.jpeg', 'RTV0PRH.jpeg', '71S643D.jpeg', 'KECHDQ9.jpeg', 'RU6PYPB.jpeg'], ['UG9Z4SQ.jpeg', 'H0Y3SYV.jpeg', '61HCFOK.jpeg', '14KE527.jpeg', 'XMSM050.jpeg', '5KFI2V3.jpeg', 'QSJMKUB.jpeg', 'S6TX0ZM.jpeg', '8JV3K1Y.jpeg', 'XI9OOI7.jpeg', 'JMWDOPM.jpeg'], ['0SAXG3I.jpeg', 'LA5HJNO.jpeg', 'PHHAUSA.jpeg', '900Z7S7.jpeg']]
such that I have:
check = [[0,0,0,0,0,0,0,0,0],[1,1,1,1,1,1], [2,2,2,2,2,2,2,2,2,2,2], [3,3,3,3]]
I want to modify it such that in index list 0 of the list of list, I'll have 0's all through, in index 1 I would have 1's all through, in index 2 I'll have 2's all through and so on like that.
for i, j in enumerate(check):
checks = [...]
I know it should be a list comprehension there, but don't just know how to go about it. That's why I have come here for help.
Here's my take with an one-liner code :
>>> [map(lambda val : i, arr) for i,arr in enumerate(check)]
The above won't quite give you the result you need. But what you can do is
arr = []
for i, j in enumerate(check):
length = j
arr.append([i]*length)
This should work perfectly, I tried it out and it worked fine. Let me know how it works for you.
Related
I have an array that I am looping over and I want to compare each element to the element next to it, and if it is larger say, then I want to do something with its index. It's clear to me that enumeration would help in this case; however I am running into an 'index out of range error':
array = [1,2,3,4]
for index,i in enumerate(array):
if array[index]>array[index+1]:
...
While I know there are other ways of doing this,
is there a way I can make the above work with enumerate? I tried to do enumerate(array)-1 ; knowing this would not work. But anything of this sort that would fix the indexing error? Thanks
I know we can easily do the above with simply using 'i' from the for loop, but just curious if I can manipulate enumeration here.
You can just shorten the range:
for i, val in enumerate(array[:-1]):
if val > array[i+1]:
# do stuff
If you don't need the index, you can use zip to the same effect:
for prev, crnt in zip(array, array[1:]):
if prev > crnt:
# do stuff not requiring index
The slicing requires O(n) extra space, if you don't want that, you can use your original approach without enumerate, but a simple range:
for i in range(len(array)-1):
if array[i] > array[i+1]:
# ...
Use zip and slice:
for i, j in zip(array, array[1:]):
print(f'i: {i} - j: {j}')
Output:
i: 1 - j: 2
i: 2 - j: 3
i: 3 - j: 4
Doing this way will set index at 0 and i at 1. A list is starting at 0 in Python. So at i=3, you are looking at array[i+1]=array[4] which does not exist ! That is why the program is saying 'index out of range error'.
Here is what I suggest if you want to stick with lists:
array = [1,2,3,4]
for i in range(len(array)-1):
if array[i]>array[i+1]:
...
If you want to manipulate the index, then it will be the current index in your loop (i). Maybe I have not understood your issue correctly but I suggest you to use numpy if you want to work with array-like objects.
Charles
What logic do you need to apply for the last element in the list?
You can use the range function instead of enumerate.
If you don't need to implement business logic to last element, then use below:
array = [1,2,3,4]
l = len(array)
for i in range(l-1):
if array[i]>array[i+1]:
...
If you do need to implement business logic to last element then use below:
array = [1,2,3,4]
l = len(array)
for i in range(l):
if i==l-1:
implemet last elemt logic
else:
if array[i]>array[i+1]:
....
How would I go about doing the following? I need to add the number in the various elements together and assign the total to a new variable. I have been trying for days without much luck. I'm not sure if the numbers have to be split from the letters first?
list = ['2H','4B']
any help would be GREATLY appreciated.
edit:
Thanks for the replies eveyrone. I dont know why I cant get this right it seems like it should be so simple.
I will give you guys some more infomration.
the list below represents to playing cards, the first number or letter is the face value ie: 2 or 3 but can be a 'K' as well which stands for king and the value for that will be ten. the second part is the card suit ie. C for Clubs or H for hearts. I need to add the face value for these two cards together and get the hand total. a More accurate list might look like this.
list1 = ['KH', '10C']
Is this helping. it will help regardless of the number position in them element.
list1 = ['2H','4B']
list1=[word for x in list1 for word in x] #== Split the elements
print(list1)
new_var=0
for value in list1:
try:
value=int(value) #=== Convert to int
new_var+=value #== Add value
except ValueError:
pass
print(new_var)
One approach, using a list comprehension along with re.findall to extract the leading digits from each list entry:
list = ['2H','4B']
nums = [int(re.findall(r'^\d+', x)[0]) for x in list] # [2, 4]
output = sum(nums) # 6
You should avoid using function names as variable names i.e. list =
There are a few ways to do this and I suggest you review the Python documentation on slicing and indexing strings.
l = ['2H','4B']
result = sum(int(x[0]) for x in l)
print(result)
result equals sum of first char of each element of the list. I have converted each indexed element zero to integer to allow addition.
You can also do it the following way:
result = 0
for x in l:
result += int(x[0])
print(result)
You can extract numbers from each string then add them
You can use
total = 0
list = ['2H','4B']
for element in list:
res = [int(i) for i in element.split() if i.isdigit()]
total += sum(res)
print(total)
I am trying to use a for loop to create a series from entries in a dataframe, however I am having difficulties getting the last element of the dataframe.
import pandas as pd
a = pd.DataFrame([0,1,2,3,4,5,6,7])
a.values[-1] # returns 7
a.values[-5:-1]# returns 3,4,5,6
a.values[-5:]# returns 3,4,5,6,7
b = []
for i in range(0,len(a)):
b.append(a.values[-(i+1):-i])
I would like for 7 to be included in the list b. I realize that when i=0, a.values gives an empty array, however I'm not sure how to fix this as I can't iterate i to be blank as shown above.
Why not just manually convert negative indices to positive indices?
for i in range(0, len(a)):
b.append(a.values[(len(a) - (i+1) - 1):(len(a) - i)])
This works because python doesn't care if your upper limit in a slice is out-of-bounds, so long as the lower-limit is in bounds.
But if you're just trying to reverse the list (which it seems like you're trying to do), have you considered b = reversed(a)?
I would like for 7 to be included in the list b
import pandas as pd
a = pd.DataFrame([0,1,2,3,4,5,6,7])
b = []
for i in range(0, len(a)):
b.append(a.iloc[i])
OR, As a one-liner:
b = [a.iloc[i] for i in range(0, len(a))]
This will remove the blank and include 7 in the list:
for i in range(0,len(a)):
b.append(a.values[-i-1])
Moring guys.
I have a question about how to append array elements with several condition.
assume i've array like this:
A=[[100,Z],[102,A],...,[9901,A]]
and another array like this:
B=[[100,-0.22,0.99],[102,-0.442,0.99],...,[9901,-1.22,4.99]]
The length of array A and B are different.
I want to append both the array elements with condition like this:
if(A[0][0]==B[0][0]):
temp = [B[0][1],B[0][2],A[0][1]]
array_new.append(temp)
I've try to append , and works , but the length of the new array is shorter than the A array.
Is something wrong with my code?
this is my code how I concat it:
for g in range(len(A)):
for h in range(len(B)):
if(B[h][0]==A[g][0]):
temp = [B[h][1],B[h][2],A[g][1]]
array.append(temp)
Thank you and have a nice day.
This matches the elements from A and B that have the same first entry in the list.
Convert B to a dictionary with the first element as the key.
The second elements of A are converted to characters, you can't define A recursive.
A=[[100,'Z'],[102,'A'],[9901,'C']]
B=[[100,-0.22,0.99],[102,-0.442,0.99],[9901,-1.22,4.99]]
B_Dict = { b[0]:b for b in B }
array_new = [ [B_Dict.get(a[0])[1],B_Dict.get(a[0])[2],a[1]] for a in A if B_Dict.get(a[0])]
print (array_new)
EDITED
If you indent correctly, length of array must same as A or shorter than A.
Fixing indentation:
for g in range(len(A)):
for h in range(len(B)):
if(B[h][0]==A[g][0]):
temp = [B[h][1],B[h][2],A[g][1]]
array.append(temp)
My partner in a summative for HS gave me this algorithm, I was hoping somebody could tell me if there is a more eloquent way of coding this..
CB is current board position(global), its a list of lists.
for a in xrange(0, 3):
for b in xrange(0, 3):
for j in xrange(1, 4):
for k in xrange(1, 4):
boxsum += CB[3a + j][3b + k]
if not(boxsum == 45):
return False
boxsum = 0
First, the following code is not indented correctly:
if not(boxsum == 45):
return False
boxsum = 0
(with the current indentation it will always fail on the first time this code is executed)
Second, in the following line:
boxsum += CB[3a + j][3b + k]
you probably meant to do:
boxsum += CB[3*a + j][3*b + k]
And last, in order to check a 3x3 part of sudoku game it is not enough to check the sum - you should also check that every number between 1-9 is present (or in other words, that all the numbers are in the range 1-9 and there is no number that appears more than once).
There are dozens of "cleaner" ways to do so.
First of all, why not use numpy for matrices, where you are obviously working with a matrix? I am assuming your numeration (which is a bit odd, why you start numerating from "1"?)
import numpy as np
CB = np.array(CB)
def constraint3x3check(CB):
return np.all(np.sum( CB[3*a+1:3*a+3, 3*b+1:3*b+3)==45 for a in range(3) for b in range(3))
Given the sum of the box equals 45, that doesn't mean there are all 1-9 numbers present.
You could for example add your numbers to set and check if the length of the set is always 9.
Since the sum 45 does not mean the answer is correct, necessarily, a different way is needed. Personally, I would join the rows into a single list and compare them to the list (1,2,...9), e.g.
#assuming this is your format...
box = [[4,2,3],[1,5,9],[8,7,6]]
def valid_box(box):
check_list = []
for row in box:
check_list += row
return list(range(1,10)) == sorted(check_list)
Although the code creating the list could also be done with list comprehension (I have no idea which one is more efficient, processor-wise)
def valid_box2(box):
return list(range(1,10)) == sorted( [item for row in box for item in row ] )
Merge list code taken from Making a flat list out of list of lists in Python