每两个字符

时间:2017-06-15 15:02:16

标签: python csv

我有一个看起来像这样的文件:

200 310 201 310 202 310 ......

基本上,这些是分组的像素坐标。因此,例如,像素号1是(200×310)。 现在,我想在每个像素上循环。我已经开始加载文件

with open('myfile.csv', 'rt') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    #Now I would like to have something like :
    for i in ???
         x,y = ???

由于

3 个答案:

答案 0 :(得分:1)

也许一种简单的方法会更好:

for i in range(0,len(spamreader),2):
   x, y = spamreader[i], spamreader[i + 1]

那是你想要的吗?

编辑:这不起作用。根据文档,你可以这样做:

while(true):
    try:
        x = spamreader.next() #.next() returns the next element as a string
        y = spamreader.next() # same
        # do stuff with it...
     except StopIteration:
        # we have read everything

答案 1 :(得分:1)

你可以这样做:

def pairwise(iterable):
    "s -> (s0,s1), (s2,s3), (s4, s5), ..."
    a = iter(iterable)
    for pair in zip(a, a):
        yield pair

with open('myfile.csv', 'rt') as csvfile:
    for line in csvfile:
        for pair in pairwise(line.split()):
            print(pair)

根据您的问题中的输入行输出:

('200', '310')
('201', '310')
('202', '310')

在Python 3中,您可以使用yield from并稍微简化pairwise()

def pairwise(iterable):
    "s -> (s0,s1), (s2,s3), (s4, s5), ..."
    a = iter(iterable)
    yield from zip(a, a)

答案 2 :(得分:0)

您可以简单地链接csv阅读器返回的行并使用成对的值

list()

由于with open('myfile.csv', 'rt') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') items = itertools.chain.from_iterable((row for row in spamreader)) for i in items: x, y = i, next(items) # the next consumes a second element 函数确实消耗了第二个元素,因此在每次迭代时,您实际上都会获得接下来的2个元素