使用 excel 作为我的数据集时使用两个 if 语句
Using two if statements while using excel as my data set
我正在尝试循环并计算'Dan'有多少次颜色'green'
我的 sheet 看起来像这样
https://imgur.com/a/ccohMbD
import xlrd
import os
#os.chdir('C:\Users\Dan\Desktop')
cwd = os.getcwd()
excelsheet1 ='Python practice book.xlsx'
book1 = xlrd.open_workbook(excelsheet1)
sheet = book1.sheet_by_index(0)
i=0
for row in range(sheet.nrows):
if str(sheet.cell(row,0).value) == "Dan" and 'green':
i=i+1
else:
pass
print('there are', i)
在此它告诉我 2,我的理解是因为 python 只是为 Dan 循环,而没有考虑我的功能。
我尝试使用代码复制我的 if 函数:
if str(sheet.cell(row,0).value) == "Dan":
if str(sheet.cell(row,0).value) == "green":
i=i+1
else:
pass
print('there are', i)
其中 python returns 0
我认为这与我如何格式化通话有关
正如 Klaus 评论的那样,"and" 并非如此。在非空字符串的情况下,它总是 return True.
下面的示例将 return 您的预期结果。我设置了 "name" 和 "color" 变量以增强可读性。
请注意,您的第二个代码示例可以正常工作,只是您没有更改第一个 "if" 和第二个之间的列索引。
import xlrd
import os
#os.chdir('C:\Users\Dan\Desktop')
cwd = os.getcwd()
excelsheet1 ='Python practice book.xlsx'
book1 = xlrd.open_workbook(excelsheet1)
sheet = book1.sheet_by_index(0)
i=0
for row in range(sheet.nrows):
name = str(sheet.cell(row,0).value)
color = str(sheet.cell(row,2).value)
if name == "Dan" and color == "green":
i=i+1
# There's no need for an "else" statement here.
print('there are', i)
我正在尝试循环并计算'Dan'有多少次颜色'green' 我的 sheet 看起来像这样 https://imgur.com/a/ccohMbD
import xlrd
import os
#os.chdir('C:\Users\Dan\Desktop')
cwd = os.getcwd()
excelsheet1 ='Python practice book.xlsx'
book1 = xlrd.open_workbook(excelsheet1)
sheet = book1.sheet_by_index(0)
i=0
for row in range(sheet.nrows):
if str(sheet.cell(row,0).value) == "Dan" and 'green':
i=i+1
else:
pass
print('there are', i)
在此它告诉我 2,我的理解是因为 python 只是为 Dan 循环,而没有考虑我的功能。 我尝试使用代码复制我的 if 函数:
if str(sheet.cell(row,0).value) == "Dan":
if str(sheet.cell(row,0).value) == "green":
i=i+1
else:
pass
print('there are', i)
其中 python returns 0 我认为这与我如何格式化通话有关
正如 Klaus 评论的那样,"and" 并非如此。在非空字符串的情况下,它总是 return True.
下面的示例将 return 您的预期结果。我设置了 "name" 和 "color" 变量以增强可读性。
请注意,您的第二个代码示例可以正常工作,只是您没有更改第一个 "if" 和第二个之间的列索引。
import xlrd
import os
#os.chdir('C:\Users\Dan\Desktop')
cwd = os.getcwd()
excelsheet1 ='Python practice book.xlsx'
book1 = xlrd.open_workbook(excelsheet1)
sheet = book1.sheet_by_index(0)
i=0
for row in range(sheet.nrows):
name = str(sheet.cell(row,0).value)
color = str(sheet.cell(row,2).value)
if name == "Dan" and color == "green":
i=i+1
# There's no need for an "else" statement here.
print('there are', i)