[英]How do I make this python code a one liner?
for _ in line:
if line == "t":
t += 1
else:
s += 1
我如何使這個 python 代碼成為一行代碼?
嘗試這個:
ts=(len([x for x in line if x=="t"]),len([x for x in line if x!="t"]))
兩個生成器語句通過line
並創建一個列表,其中包含或不是"t"
的字母,然后用len
和一些括號包圍每個列表,以在ts
創建一個元組。 變量t
和s
可以像ts[0]
和ts[1]
一樣賦值。
使用 count() 怎么樣? line.count("t") 將返回字符串 "t" 在該行中出現的次數?
>>> line = "tstststs"
>>> t, s = line.count("t"), line.count("s")
>>> t
4
>>> s
4
def bar(line):
t = s = 0
for _ in line:
if line == "t":
t += 1
else:
s += 1
return t, s
相當於:
def bar(line):
t, s = (1, 0) if line == "t" else (0, len(line))
return t, s
測試一下:
import random
NUM_TESTS = 100
MAX_STR_LEN = 10
def get_rand_chs(l):
for _ in range(l):
o = random.randint(ord('a'), ord('z'))
yield chr(o)
def gen_rand_str():
l = random.randint(0, MAX_STR_LEN)
yield ''.join(ch for ch in get_random_chs(l))
for _ in range(NUM_TESTS):
rand_str = get_rand_str()
assert bar(rand_str) == foo(rand_str)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.