簡體   English   中英

如何將此代碼放入一個打印 function (或行)?

[英]How do I put this code into one print function (or line)?

所以我想把這段代碼寫成一行。 我不知道如何創建兩個隨機列表,然后在一行中打印出兩個列表中的公共數字。 我不熟悉將代碼放在一行中,我不知道這是否可能。

這是我擁有的代碼:

import random
a, b = random.sample(range(1, 50), 30), random.sample(range(1, 50), 30)

print([x for x in a for y in b if x == y])

這是我的嘗試:

import random
print([[a = random.sample(range(1, 50), 30)], [b = random.sample(range(1, 50), 30)], x for x in a for y in b if x == y])

只需嵌入定義,因為不需要變量:

import random
print([x for x in random.sample(range(1, 50), 30) for y in random.sample(range(1, 50), 30) if x == y])

您也可以用__import__("random")替換random ,然后如果您想要一個真正的單行,則在第一行去掉import random

搭配套裝:

>>> import random
>>> {*random.sample(range(1, 50), 30)}.intersection({*random.sample(range(1, 50), 30)})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM