Python为什么跳过elif语句

huangapple go评论64阅读模式
英文:

Why python skips elif statement

问题

我尝试做的是让用户输入一组用空格分隔的值,读取它们,与数据框进行正确比较并相应地打印文本。
这可能看起来是一个简单的任务,但实际上花了我很多时间来挣扎。
奇怪的地方:

  1. 单独的 else 语句正常工作,但其格式与 if 语句不同
  2. if 语句的格式似乎是正确的,但它的工作方式不正确。
    无论我输入什么,它总是打印出'所有数字都在数据框中'。
  3. 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:

  1. else statement by itself is working properly, but its formatting differs from if statement
  2. 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.
  3. 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
          )

在这个修正后的代码中,我们将 in1uniq_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 bools, 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 bools.

huangapple
  • 本文由 发表于 2023年6月13日 04:50:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76460239.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定