相关疑难解决方法(0)

如何针对值测试多个变量?

我正在尝试创建一个函数,将多个变量与一个整数进行比较,并输出一个由三个字母组成的字符串.我想知道是否有办法将其翻译成Python.所以说:

x = 0
y = 1
z = 3
mylist = []

if x or y or z == 0 :
    mylist.append("c")
if x or y or z == 1 :
    mylist.append("d")
if x or y or z == 2 :
    mylist.append("e")
if x or y or z == 3 : 
    mylist.append("f")
Run Code Online (Sandbox Code Playgroud)

这将返回一个列表

["c", "d", "f"]
Run Code Online (Sandbox Code Playgroud)

这样的事情可能吗?

python comparison boolean-logic if-statement match

594
推荐指数
19
解决办法
19万
查看次数

检查另一个字符串中是否存在多个字符串

如何检查数组中的任何字符串是否存在于另一个字符串中?

喜欢:

a = ['a', 'b', 'c']
str = "a123"
if a in str:
  print "some of the strings found in str"
else:
  print "no strings found in str"
Run Code Online (Sandbox Code Playgroud)

该代码不起作用,只是为了展示我想要实现的目标.

python arrays string exists

338
推荐指数
6
解决办法
28万
查看次数

为什么`a == b或c或d`总是评估为True?

我正在编写一个拒绝访问未授权用户的安全系统.

import sys

print("Hello. Please enter your name:")
name = sys.stdin.readline().strip()
if name == "Kevin" or "Jon" or "Inbar":
    print("Access granted.")
else:
    print("Access denied.")
Run Code Online (Sandbox Code Playgroud)

它按预期授予对授权用户的访问权限,但它也允许未经授权的用户访问!

Hello. Please enter your name:
Bob
Access granted.
Run Code Online (Sandbox Code Playgroud)

为什么会这样?我明确表示,只有在与nameKevin,Jon或Inbar相同时才授予访问权限.我也尝试过相反的逻辑if "Kevin" or "Jon" or "Inbar" == name,但结果是一样的.

python boolean boolean-expression

96
推荐指数
3
解决办法
2万
查看次数

将一个字符串与另一个字符串的多个子字符串进行比较

有没有另一种更简单的方法来编写代码,基本上检查字符串的每个字符 'abcde'

if input == 'a' or input == 'ab' or input == 'abc' or input == 'abcd' or input == 'abcde':
    return True
Run Code Online (Sandbox Code Playgroud)

python string string-comparison

30
推荐指数
4
解决办法
762
查看次数

多条件python

我想做一个函数来计算字符串中的辅音,所以我试着这样做:

def vowel_count(foo):
  count = 0
  for i in foo:
    if not i == 'a' and i == 'e' and i ... and i == 'O' and i == 'U':
      count += 1
return count
Run Code Online (Sandbox Code Playgroud)

但这样做非常难看和繁琐,更多的条件更多.有没有办法将它们组合在一起?

python if-statement

2
推荐指数
1
解决办法
278
查看次数

在循环中跳过一组值(在数组中) - Python3

我有一个循环读取数据,但编号不连续.因此,我想跳过具体的值.但我只知道如何跳过一个,而不是一组值.这是我的示例代码:

for n in [x for x in range(2,m) if x!=9]:
    if n < 10:
        stationsnr = '00'+np.str(n)
    elif n < 100:
        stationsnr = '0'+np.str(n)
    else:
        stationsnr = np.str(n)
Run Code Online (Sandbox Code Playgroud)

但是代替"x!= 9"我需要像x!=其中一个值[9,10,12,16,......](编辑:值存储在列表中).有什么建议?

python loops for-loop python-3.x

0
推荐指数
1
解决办法
300
查看次数