Reputation: 1694
Hi I want to slice a large list data like the following list, one part is 20%(consecutive) part of the list, another is left. I just know to get the 20% part but how to get the left part of list in a loop. Thanks my code is following. for example, when X1 = [ '1', '2'], X2 = ['3','4','5','6', 7','8','9','10']. then X1 = ['2','3'], and X2 = ['1','4','5','6', 7','8','9','10'], .........
X = ['1','2','3','4','5','6', 7','8','9','10']
index = 0
for i in range(9):
X1 = X[i:(i+2)]
X2 = X[]
Upvotes: 0
Views: 54
Reputation: 3091
I would like to offer a similar, but more robust solution. You say you need to get 20% of the large list. While slice size of 2 works for a list with 9 members, you will obviously need to increase it for a larger list. If you do not know how many members a list will have, it can be particularly tedious and error prone. Hence, I would suggest something like this:
import math
X = ['1','2','3','4','5','7','8','9','10']
# Calculate how many members a 20% slice should have
twenty = int(math.ceil(len(X) * 20 / 100.0))
for i in range(len(X)):
X1 = X[i:(i+twenty)]
X2 = X[:i] + X[(i+twenty):]
What this does is calculate how many members ~20% slice should have, and then apply this number to list slicing. Note, however, that math.ceil()
always rounds up, so if you have something like 2.1, it would end up being 3.0 (meaning that some slices will have slightly more members than 20%, e.g. 22%). If you want to round in a more familiar fashion (2.49 -> 2; 2.5 -> 3), round() would be a good choice.
Upvotes: 1
Reputation: 10631
You can fetch the second part by telling from what index you would like to start untill the end.
X = ['1','2','3','4','5','7','8','9','10']
index = 0
for i in range(9):
X1 = X[i:(i+2)]
X2 = X[:i] + X[(i+2):]
Upvotes: 1