HelloWorld HelloWorld - 1 month ago 10
Python Question

How can I take out data of lists?

I want to calculate the difference between the second last number (

x[1]
) and the other numbers of the different items in the list (
list
).

In the first item of the list, it should be 19-13 (= 6), 19-16 and 19-19. The problem is that the items in the list consist of 3 or 4 (sometimes 5/6) numbers.

list = [([(13, 400), (14, 700), (19, 700)], 19, 1800),
([(24, 250), (28, 650), (35, 100), (43, 600)], 43, 1600),
([(46, 450), (48, 600), (78, 450)], 78, 1500),
([(79, 650), (88, 400), (92, 600), (96, 50)], 98, 1700)]

1= []
for x in list:
1.append(x[0][0][0])
print "1", 1

2= []
for xin list:
2.append(x[0][1][0])
print "2", 2

3= []
for xin list:
3.append(x[0][2][0])
print "3", 3

4= []
for xin list:
4.append(x[0][3][0])
print "4", 4

time= []
for xin list:
time.append(x[1])
print time


Result:

1 [13, 24, 46, 79]
2 [14, 28, 48, 88]
3 [19, 35, 78, 92]
Traceback (most recent call last):
File "test.py", line 26, in <module>
4.append(order[0][3][0])
IndexError: list index out of range


The error only appears if the list consist of items which consist of less than 4 items. Because then the
[3]
in
[0][3][0]
will find an "empty item".




Thank you nigel222, both worked but I used your first suggestion. To create two lists of the same length i used the else: function:

for x in list:
if len(x[0]) >= 4:
4.append(x[0][3][0])
else:
fourthorder.append(order[1])


Afterwards I calculate the difference between x[1] and the 4 lists, so if else: is used, x[1]-x[1] gives 0.

Answer

Two main ways to go: test in advance, or handle the exception, always assuming you know exactly what to do when there is no fourth item.

Check first:

fourthorder_arrival_of_batch = []
for order in servedbook:
    if len( order[0]) > 3:
        fourthorder_arrival_of_batch.append(order[0][3][0])
    #else:
        #append a default value if desired
print "4", fourthorder_arrival_of_batch

handle exception

fourthorder_arrival_of_batch = []
for order in servedbook:
    try:
        fourthorder_arrival_of_batch.append(order[0][3][0])
    except IndexError:
        #append a default value if desired, or
        pass
print "4", fourthorder_arrival_of_batch

Exceptions should be the unusual case, because a handled exception is more expensive than a simple test done in advance. But if less than (say) ten percent are exceptional, then this will rarely if ever matter and if the test is not simple, then handling the exceptions may be more efficient.