还有另一种更简单的方法来编写代码,该方法基本上检查字符串'abcde'
的每个字符
if input == 'a' or input == 'ab' or input == 'abc' or input == 'abcd' or input == 'abcde':
return True
答案 0 :(得分:37)
这应该和您放的东西一样。
func encodeWebp(m3u8: String, completed: () -> Void){
guard let sessionid = sessionID else {return}
let lastName: String = m3u8
let docFolder = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let output = URL(fileURLWithPath: docFolder + "/OfflineSession/\(sessionid)").appendingPathComponent("\(lastName).mp4")
let outputTxt = URL(fileURLWithPath: docFolder + "/OfflineSession/\(sessionid)").appendingPathComponent("\(lastName).txt")
let fileName = "\(m3u8)_ffmpegData.txt"
let textFile = URL(fileURLWithPath: docFolder).appendingPathComponent("OfflineSession/\(sessionid)/\(fileName)")
let ffmpegCommand = "-f concat -i \(textFile) -c:v copy -c:a copy \(output) -progress \(outputTxt)"
MobileFFmpeg.execute(ffmpegCommand)
completed()
}
答案 1 :(得分:12)
不要命名变量input
,因为它将隐藏内置函数input()
。这被认为是不好的做法,并且很容易选择另一个变量名。
您可以使用set来检查输入是否与任何子字符串匹配:
lookups = {'a', 'ab', 'abc', 'abcd', 'abcde'}
my_input = input()
if my_input in lookups:
return True
我们还可以使用集合理解来生成该集合:
characters = 'abcde'
lookups = {characters[:i] for i in range(1, len(characters) + 1)}
my_input = input()
if my_input in lookups:
return True
对于大型组合,在列表上使用组合的好处是您可以进行恒定时间 O(1)查找以进行搜索。这比使用列表要好得多,后者将为您提供线性 O(N)查找。
答案 2 :(得分:6)
有多种可爱的方法可以做到这一点。
startwith
可能是效率最高的,但是它们也应该起作用:
使用lstrip
:
return 'abcde'.lstrip(input)!='abcde'
使用list comprehension
:
return any(['abcde'[:i+1] == input for i in range(len('abcde'))])
使用regex
:
pattern = re.compile('^'+input)
return bool(pattern.match('abcde'))
或者只是:
return 'abcde'[:len(input)]==input
答案 3 :(得分:5)
您可能会尝试这样的事情:
return 'abcde'.startswith(input)
让我知道这是否有帮助!
答案 4 :(得分:0)
您可以尝试以下方法:
If input in ['a', 'ab', 'abc', 'abcd', 'abcde']:
return True
else:
return False