[英]Python-How to display the for loop only once?
I am trying to iterate column of alphabet in 'new.xlsx', and if the alphabet exists in 'original.xlsx', then copy the data and paste into new.xlsx.我正在尝试迭代“new.xlsx”中的字母列,如果“original.xlsx”中存在字母表,则复制数据并粘贴到 new.xlsx 中。 The code following is what I have done.
以下代码是我所做的。
import openpyxl
dappend = openpyxl.load_workbook('C:/Users/User/Desktop/original.xlsx', data_only=True)
dp1 = dappend.active
consider = openpyxl.load_workbook('C:/Users/User/Desktop/new.xlsx', data_only=True)
cd1 = consider.active
li2 = []
for c in range(2,cd1.max_row+1):
name = cd1.cell(row=c,column=4).value
for d in range(2,dp1.max_row+1):
if cd1.cell(row=c,column=4).value == dp1.cell(row=d,column=4).value:
li2=[dp1.cell(row=d,column=4).value,dp1.cell(row=d,column=5).value,dp1.cell(row=d,column=6).value,dp1.cell(row=d,column=7).value]
print(li2)
d = d + 1
else:
continue
c = c + 1
My output is:我的输出是:
['A', None, 'Jonathan', None]
['A', '', 'Jonathan', '']
['B', None, 'Cassandra', None]
['B', None, 'Rose', None]
['B', 'Tyler', None, None]
['B', '', 'Cassandra', '']
['B', '', 'Rose', '']
['B', 'Tyler', '', '']
['C', 'Sam', None, None]
['C', 'Sam', '', '']
['D', 'Jeremy', None, None]
['D', 'Jeremy', '', '']
but I expected the output to be like...但我希望输出像......
['A', '', 'Jonathan', '']
['B', '', 'Cassandra', '']
['B', '', 'Rose', '']
['B', 'Tyler', '', '']
['C', 'Sam', '', '']
['D', 'Jeremy', '', '']
Please help...请帮忙...
First a comment: the lines c = c+1 and d = d+1 do nothing since in the beggining of the loop they get redefined as the next item in your list: range(2,5) = (2,3,4)首先评论:行 c = c+1 和 d = d+1 什么都不做,因为在循环开始时,它们被重新定义为列表中的下一项: range(2,5) = (2,3,4 )
Now to your solution: I would suggest you add an if before the print command现在到您的解决方案:我建议您在打印命令之前添加一个 if
if None in li2 :
# do nothing
else:
print(li2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.