【问题标题】:Python find elements in a list and return true or falsePython 在列表中查找元素并返回 true 或 false
【发布时间】:2021-09-12 10:23:56
【问题描述】:

我陷入了字符串列表中的研究元素。 我用数字(字符串)输入文本,然后尝试查找“+”或“-”之类的符号 我的代码:

 Lista=np.array([s for s in text]) 
 y=np.where(Lista=='+') 
 if y==[]: /*so, if it's void*/
        print("any elements")
  else:
        print("yes")

我尝试这样做,因为我想创建一个计算器,而此时我可以只做 + 操作(在我的代码的第二部分,我使用 split("+") 并将字符串转换为 int )。 所以我想用 if, else, elif 创建一个类似于 switch case 的结构。类似于: if ('+') -> 执行此操作,否则 if ('-')-> 执行此操作,ecc。 显然,我想创建 4 y=np.where(lista='+'/='-'/=''...) 并为每个人创建 if else。所以如果在口渴的情况下我找不到'+':通过。如果在第二种情况下我找不到'-':通过。如果在第三种情况下我找到 '' :做 moltiplicato。我尝试用 y==[] 或 y!=[] 来做这些事情。当我打印 y=np.where(lista='+') 的结果时,我看到它返回数组 [1] 或数组 [],但是如果我尝试将此作为条件,它就不起作用.

示例。在我的计算器中,我写了 4+5。 4+5 它保存在一个名为 text 的变量中。我在 Lista=np.array([s for s in text]) 中转换了 var 文本。 在我尝试使用 y=np.where(Lista=='+') 在 Lista 中搜索符号“+”之后。在控制台中,我看到它位于第一个位置,因此在数组 [1] 中。所以用 if 条件

    if y==[]: 
       print("the list it's void") 
       pass
    else: print("the elemnt it's at firt position")
    Lista=np.array([s for s in text.split('+')])
    v=[int(v) for v in Lista]
    c=sum(v)
    print(c)

但是,当我写 4+5 时,在 y==[] 条件下,打印出的列表是无效的,但事实并非如此,因为在 arrayIndex 我看到位置 y[1] 有一个 '+ '。

Java 代码示例。我想在 Python 中也一样 公共类主 {

    public static void main(String[] args) {
        boolean findSymbol=true;

        char [] p = {31, 28, 31, 30, 31, 30, 31, '-'};
        for (char c : p) {
            if (c == '+') {
                findSymbol= true;
                System.out.println("let's do something");
            } else
                findSymbol = false;
            System.out.println("Nope");

            if (c == '-') {
                findSymbol=true;
                System.out.println("let's do something");
                
            }else
                findSymbol = false;
            System.out.println("Nope");

            }
        }

}

【问题讨论】:

  • 类似于 switch case 的结构 你对“switch case”的理解是什么?你的意思是来自 JavaScript 的 switch 还是其他什么?
  • @Daweo 是的,没错。我知道在 Python 中不存在 switch case,所以所有的事情都必须用 if、else 和 elif 来完成。

标签: python numpy arraylist


【解决方案1】:

Python 3.10 有一个match 语句,它是switch 的pythonic 版本。 无论如何,正如您所说,您可以使用if ... elif ... else 获得相同的结果:

if s=='+':
    ##handle addition
elif s=='-':
    ##handle subtraction
elif s=='*':
    ##handle multiplication
##etc
else:
    ##did not match any previous check, raise exception or something

【讨论】:

    猜你喜欢
    • 2011-12-23
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    相关资源
    最近更新 更多