我正在尝试创建一个函数,将多个变量与一个整数进行比较,并输出一个由三个字母组成的字符串.我想知道是否有办法将其翻译成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)
这样的事情可能吗?
如何检查数组中的任何字符串是否存在于另一个字符串中?
喜欢:
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)
该代码不起作用,只是为了展示我想要实现的目标.
我正在编写一个拒绝访问未授权用户的安全系统.
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,但结果是一样的.
有没有另一种更简单的方法来编写代码,基本上检查字符串的每个字符 'abcde'
if input == 'a' or input == 'ab' or input == 'abc' or input == 'abcd' or input == 'abcde':
return True
Run Code Online (Sandbox Code Playgroud) 我想做一个函数来计算字符串中的辅音,所以我试着这样做:
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)
但这样做非常难看和繁琐,更多的条件更多.有没有办法将它们组合在一起?
我有一个循环读取数据,但编号不连续.因此,我想跳过具体的值.但我只知道如何跳过一个,而不是一组值.这是我的示例代码:
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 ×6
if-statement ×2
string ×2
arrays ×1
boolean ×1
comparison ×1
exists ×1
for-loop ×1
loops ×1
match ×1
python-3.x ×1