英文:
Why python skips elif statement
问题
我尝试做的是让用户输入一组用空格分隔的值,读取它们,与数据框进行正确比较并相应地打印文本。
这可能看起来是一个简单的任务,但实际上花了我很多时间来挣扎。
奇怪的地方:
- 单独的 else 语句正常工作,但其格式与 if 语句不同
- if 语句的格式似乎是正确的,但它的工作方式不正确。
无论我输入什么,它总是打印出'所有数字都在数据框中'。 - elif 语句从未被识别
我将输入的字符串转换为列表,可以在代码示例中看到。
所以,这显然与数据类型无关。
任何帮助将不胜感激!
import pandas as pd
in1 = input("选择一些以空格分隔的数字:")
in1 = in1.strip()
result = pd.DataFrame([1, 1, 1, 2, 3, 3, 4, 5], columns=['Numbers'])
uniq_numbers = list(result.Numbers.unique())
print(type(in1))
in1 = in1.split()
for i in range(len(in1)):
in1[i] = int(in1[i])
print(type(in1))
if all(result[(result['Numbers'].isin([in1]))]):
print('所有数字', in1, '都在数据框中:', uniq_numbers)
elif not all(result['Numbers'].isin(in1)):
print('在数据框中未找到任何数字!', in1, uniq_numbers)
else:
print('输入的一些数字:', in1, '不在数据框中,请注意。\n',
'有效数字:',
set(in1).intersection(result),
'\n 在数据框中未找到的数字:',
(set(in1) - set(result))
)
输入: 6 7
输出:
所有数字都在数据框中
['6', ' ', '7']
英文:
What I am trying to do is to let user input a set of values separated with spaces, read them, compare correctly with the dataframe and print text accordingly.
What may look like a simple task turned out in many hours of struggling.
What is strange:
- else statement by itself is working properly, but its formatting differs from if statement
- if statement formatting seems correct, but it doesn't work right.
It always prints that 'All numbers are in dataframe' no matter what I type in. - elif statement is never recognized
I converted input str to list, which can be seen in the code example.
So, this is clearly not related to data type.
Any help will be very appreciated!
import pandas as pd
in1 = input("Choose certain numbers separated with spaces:")
in1 = in1.strip()
result = pd.DataFrame([1, 1, 1, 2, 3, 3, 4, 5], columns=['Numbers'])
uniq_numbers = list(result.Numbers.unique())
print(type(in1))
in1 = in1.split()
for i in range(len(in1)):
in1[i] = int(in1[i])
print(type(in1))
if all(result[(result['Numbers'].isin([in1]))]):
print('All numbers', in1, ' are in dataframe:', uniq_numbers)
elif not all(result['Numbers'].isin(in1)):
print('No numbers', in1, ' were found in dataframe!', uniq_numbers)
else:
print('Some of the numbers entered:', in1, 'are NOT in dataframe, be aware. \n',
'Valid number/s:',
set(in1).intersection(result),
'\n Number/s that were NOT found in dataframe:',
(set(in1) - set(result))
)
Input: 6 7
Output:
All numbers are in dataframe
['6', ' ', '7']
答案1
得分: 1
请尝试以下操作:
我认为这将解决您的问题:
import pandas as pd
in1 = input("选择一些以空格分隔的特定数字:")
in1 = in1.strip()
result = pd.DataFrame([1, 1, 1, 2, 3, 3, 4, 5], columns=['Numbers'])
uniq_numbers = list(result.Numbers.unique())
print(type(in1))
in1 = in1.split()
for i in range(len(in1)):
in1[i] = int(in1[i])
print(type(in1))
in1_set = set(in1)
uniq_numbers_set = set(uniq_numbers)
if in1_set.issubset(uniq_numbers_set):
print('所有数字', in1, '都在数据框中:', uniq_numbers)
elif not in1_set.intersection(uniq_numbers_set):
print('在数据框中未找到任何数字:', in1, uniq_numbers)
else:
print('输入的一些数字:', in1, '不在数据框中,请注意。\n',
'有效数字:',
in1_set.intersection(uniq_numbers_set),
'\n 未在数据框中找到的数字:',
in1_set - uniq_numbers_set
)
在这个修正后的代码中,我们将 in1
和 uniq_numbers
转换为集合,并使用 issubset
方法来检查 in1
中的所有数字是否都在数据框中。我们还使用 intersection
方法来检查 in1
中的任何数字是否在数据框中。
英文:
Please try the following:
I think it will solve your problem:
import pandas as pd
in1 = input("Choose certain numbers separated with spaces:")
in1 = in1.strip()
result = pd.DataFrame([1, 1, 1, 2, 3, 3, 4, 5], columns=['Numbers'])
uniq_numbers = list(result.Numbers.unique())
print(type(in1))
in1 = in1.split()
for i in range(len(in1)):
in1[i] = int(in1[i])
print(type(in1))
in1_set = set(in1)
uniq_numbers_set = set(uniq_numbers)
if in1_set.issubset(uniq_numbers_set):
print('All numbers', in1, ' are in dataframe:', uniq_numbers)
elif not in1_set.intersection(uniq_numbers_set):
print('No numbers', in1, ' were found in dataframe!', uniq_numbers)
else:
print('Some of the numbers entered:', in1, 'are NOT in dataframe, be aware. \n',
'Valid number/s:',
in1_set.intersection(uniq_numbers_set),
'\n Number/s that were NOT found in dataframe:',
in1_set - uniq_numbers_set
)
In this corrected code, we convert in1
and uniq_numbers
to sets and use the issubset
method to check if all numbers in in1
are in the DataFrame. We also use the intersection
method to check if any numbers in in1
are in the DataFrame.
答案2
得分: 1
有两个主要问题。您没有测试列表中的所有数字是否在数据帧中,而是测试数据帧中的所有数字是否在列表中。if
语句的问题在于,作为all
函数的参数,您没有使用一个bool
的可迭代对象,而是一个对象,这里是数据帧。
要测试列表中的所有数字是否在数据帧中,您可以使用numpy
:
import numpy as np
import pandas as pd
result = pd.DataFrame([1, 1, 1, 2, 3, 3, 4, 5], columns=['Numbers'])
numbers = [1, 3, 5]
mask = np.isin(numbers, result['Numbers'].unique())
if np.all(mask):
print('所有数字都存在')
elif not np.any(mask):
print('没有数字存在')
else:
print('部分数字存在')
要知道列表中哪些数字在数据帧中存在,您可以使用mask
变量。如果mask[i]
为True
,则数字numbers[i]
在数据帧中存在。如果将数字转换为numpy
数组,您可以简单地获取所有存在的数字,如下所示:
numbers_present = np.array(numbers)[mask]
这是可能的,因为您可以使用bool
来索引numpy
数组。
英文:
There are two major problems. You are not testing whether all numbers in the list are in the data frame, but rather if all numbers in the data frame are in the list. The problem with the if
statement is that as the argument of the all
function you are not using an iterable of bool
s, but rather an object, data frame in this case.
To test whether all numbers in the list are in the data frame you can use numpy
:
import numpy as np
import pandas as pd
result = pd.DataFrame([1, 1, 1, 2, 3, 3, 4, 5], columns=['Numbers'])
numbers = [1, 3, 5]
mask = np.isin(numbers, result['Numbers'].unique())
if np.all(mask):
print('All numbers present')
elif not np.any(mask):
print('None numbers present')
else:
print('Some numbers present')
To know which numbers from the list are present in the data frame, you can use the mask
variable. Number numbers[i]
is present in the data frame if mask[i]
is True
. If you transform numbers to numpy
array, you can simply get all present numbers as
numbers_present = np.array(numbers)[mask]
This is possible, because you can index numpy
arrays using bool
s.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论