嵌套在for循环中的python只执行一次 [英] python nested for loop only executes once

查看:784
本文介绍了嵌套在for循环中的python只执行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个csv文件。我在一个csv中获取一个单元格的值,然后在另一个csv中进行比较。下面是我的代码:

  f = open('test1.csv')
x = open('test2.csv ')

csv_f = csv.reader(f)
csv_x = csv.reader(x)

for csv_f中的行:
a = row [ 1]
b = row [2]
用于csv_x的行:
如果a在nrow [0]和b在nrow [1]:
打印nrow [0]

现在,上面的代码仅打印a和b的第一个值。随后,对于a和b的其他值,它不会通过第二次for循环。知道是什么问题吗?

解决方案

函数

  csv_x = csv.reader(x)

返回文件对象。 / p>

当它循环到结尾时遍历它。



所以您无法遍历再次



要克服此问题,您可以使用这种方式

  f = open('test1.csv')


csv_f = csv.reader(f)


for csv_f中的行:
a = row [1]
b = row [2]
csv_x = csv.reader(open('test2.csv'))#在此处为cv_x中的nrow分配

如果a inrow [0]和b inrow [1]:
打印nrow [0]


I have 2 csv files. I am getting the value of a cell in one csv and comparing with all in another. Below is my code:

f = open('test1.csv')
x = open('test2.csv')

csv_f = csv.reader(f)
csv_x = csv.reader(x)

for row in csv_f:
    a = row[1]
    b = row[2]
    for nrow in csv_x:
        if a in nrow[0] and b in nrow[1]:
           print nrow[0]

Now the above code only prints for the first value of a and b. Subsequently, it is not going through the 2nd for loop for other values of a and b. Any idea what's the issue?

解决方案

The function

csv_x = csv.reader(x)

Returns a file object.

When you loop through it once it goes to the end.

So you can not be able to loop through it again

To overcome this problem you could use this way

f = open('test1.csv')


csv_f = csv.reader(f)


for row in csv_f:
    a = row[1]
    b = row[2]
    csv_x = csv.reader(open('test2.csv')) # assign here
    for nrow in csv_x:
        if a in nrow[0] and b in nrow[1]:
           print nrow[0]

这篇关于嵌套在for循环中的python只执行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆