感谢您抽出宝贵时间阅读本文。我正在编写一个python脚本,它将检查一个csv文件中的电话号码是否在另一个csv文件中。现在我只想尝试打印比较
num1 == num2
这是一种蛮力方法。所以另一个例子是如果有两个数组arr1 = [1,2,3]和arr2 = [4,5,6]我希望它打印出来像这样:
1 4
1 5
1 6
2 4
2 5
2 6
...
问题: 当我出于某种原因运行此代码时,与子循环的比较只发生一次,然后它只打印出父循环的其余部分,而不再运行子循环,我无法弄清楚原因。所以看起来基本上是这样的:
1 4
1 5
1 6
2
3
然后结束。知道为什么吗?
代码
def get_number(filter):
try:
filter = re.sub('-', '', filter)
filter = re.sub(' ', '', filter)
filter = re.sub('\)', '', filter)
filter = re.sub('\(', '', filter)
filter = filter.replace("+", "")
if filter[:1] == "1":
filter = filter[1:]
if len(filter) != 10:
filter = None
if filter != None:
return int(filter)
except ValueError:
print("Oops! That was no valid number. Try again...")
with open('file1.csv') as csvfile, open('file2.csv') as resultscsvfile:
input1 = csv.reader(csvfile, delimiter=',')
input2 = csv.reader(resultscsvfile, delimiter=',')
for row in input1:
filter = row[29]
num1 = get_number(filter)
print("Num 1: " + str(num1))
if num1 != None and len(str(num1)) == 10:
for row2 in input2:
filter2 = row2[6]
num2 = get_number(filter2)
if num2 != None and len(str(num2)) == 10:
print(str(num1) + " == " + str(num2))
PS get_number函数正在移除所有其他字符和空格,以便在数字之间进行比较,因为人们经常以不同方式格式化电话号码。
答案 0 :(得分:1)
迭代器只能使用一次。 移动:
with open('file2.csv') as resultscsvfile:
input2 = csv.reader(resultscsvfile, delimiter=',')
在for row in input1:
循环内,每次想要遍历所有input2行时重新创建它。
顺便说一下,num2 != None
是不鼓励的。请改用num2 is not None
。