简体   繁体   English

使用map函数在列表中的奇数位置获取列表元素

[英]To get the list elements at odd places in a list made by using map function

This is the code that I have been trying. 这是我一直在尝试的代码。 It reads a .txt file which contains two lists. 它读取一个.txt文件,其中包含两个列表。 which are respectively read by D1 and D2. 它们分别由D1和D2读取。 In D2, I need the elements at odd position only. 在D2中,我只需要将元素放在奇数位置。 The code that I have tried is given below and it doesn't give me the required output. 下面给出了我尝试过的代码,但没有提供所需的输出。 Here is the code: 这是代码:

import cv2
import numpy


fo = open("Test_input0.txt","r")
D1=[map(int, fo.readline().split())]
D2=[map(int, fo.readline().split())]
d2 = D2[1::2]


print d2

The output it gives is: 它给出的输出是:

[ ]

The .txt file content is in the following format: .txt文件的内容采用以下格式:

1 2 1 3 7 6 2 9 8 1 5 4
5 10 6 11 15 15                

map() returns a list, which you then wrap in another list with [] . map()返回一个列表,然后使用[]将其包装在另一个列表中。 When you try 当你尝试

d2 = D2[1::2]

you are trying to slice from index 1 a list containing a single item. 您正在尝试从索引1分割包含单个项目的列表。 Therefore you will get an empty list returned. 因此,您将返回一个空列表。

You can correct it by removing the surrounding [] : 您可以通过删除周围的[]来纠正它:

D1= map(int, fo.readline().split())
D2= map(int, fo.readline().split())

Or, generally considered to be more Pythonic, a list comprehension: 或者,通常被认为是更Python化的列表理解:

D1 = [int(x) for x in fo.readline().split()]
D2 = [int(x) for x in fo.readline().split()]

Now D2[1::2] should give you the items in D2 at odd indexes. 现在, D2[1::2]应该为您提供D2中奇数索引处的项目。

You can even combine both operations in one list comprehension: 您甚至可以将两个操作合并为一个列表理解:

D2 = [int(x) for x in fo.readline().split()[1::2]]

which has the advantage of converting only the required values to integers. 这具有仅将所需值转换为整数的优点。

This should work: 这应该工作:

fo = open("Test_input0.txt","r")
D1 = [int(x) for x in next(fo).split()]
D2 = [int(x) for x in next(fo).split()]
D2 = D2[1::2]

The only problem you had is the extra [] : 您遇到的唯一问题是多余的[]

Change: 更改:

D1=[map(int, fo.readline().split())]

into: 成:

D1 = map(int, fo.readline().split())

And it should work too. 它也应该起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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