简体   繁体   中英

Python, how to print specific items from lists in lists?

I am trying to print the first and last item of all the lists inside my list of lists num_list .

num_list = [[1,2,3],[10,20,30],[100,200,300]]

for x in range(0,3):
    for y in range(0,1) and range(2,3):
        print(num_list[x][y])

But this is just printing 3,30,300 and skipping the 1,10 and 100 .

What is a good way to solve this problem?

Use indexing.

Ex:

num_list = [[1,2,3],[10,20,30],[100,200,300]]

for i in num_list:
    print(i[0], i[-1])   #i[-1] == negative indexing. 

Output:

1 3
10 30
100 300

You don't need to use range to achieve your task.
Anyway, even if you would like to, there is a mistake in your code in the line

range(0,1) and range(2,3)

By definition and returns the first value which is False, otherwise if there is not, it returns the last value in the expression.
Thus, in your case it only returns range(2,3) .

Indeed,

range(0,1) and range(2,3)

returns

range(2, 3)

since bool(range(0,1)) and bool(range(2,3)) are both evaluated as True.
This is why they are both non-empty sequences. Indeed bool(range(2,2)) would be evaluated as False being empty. For more details see the documentation .

You should rather write something like

import itertools

num_list = [[1,2,3],[10,20,30],[100,200,300]]

for x in range(0,3):
    for y in itertools.chain(range(0,1), range(2,3)):
        print(num_list[x][y])

using itertools.chain .

Probably the smallest solution:

num_list = [[1,2,3],[10,20,30],[100,200,300]]
for x in num_list:
    print(x[0], x[-1])

range(0,1) 和 range(2,3) 返回 => range(2,3)

num_list = [[1, 2, 3], [10, 20, 30], [100, 200, 300]]

for each in num_list:
    print (each[0], each[-1])
num_list = [[1,2,3],[10,20,30],[100,200,300]]

for x in range(0,3):

    for y in range(len(num_list[x])):
        if y==0 or y==2:
            print(num_list[x][y])

you can use above code

this is an answer based on the original solution but it is not the best one

num_list = [[1,2,3],[10,20,30],[100,200,300]]

for x in range(0, len(num_list)):

    for y in range(0,3,2): #where the change should be
        print(num_list[x][y],end=' ') #display the results in one line

Other solution if you want short oneliners:

3 oneliner solutions if printing in one line is good for you:

print(*[num for elem in vec for num in elem[0:3:2]])

print(*[num for elem in vec for num in elem[0:1]+elem[2:3]])

print(*[num for elem in vec for num in elem[0:1]+elem[-1:]])

Output:

1 3 10 30 100 300

or to print one number per line:

print('\n'.join([str(num) for elem in vec for num in elem[0:3:2]]))

1
3
10
30
100
300

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM