random.choice逐字打印

时间:2018-03-14 01:53:49

标签: python python-3.x

我在一个小项目上工作,我有一个包含大约20张照片的文件夹。我使用os.listdir创建了一个for循环,并将所有照片名称正确打印到控制台中。

主要问题是我希望它随机选择文件夹中的一张照片并打印出其名称。发生的事情是,它正在做其他事情,并在控制台上打印多个单字母字符。

for photos in os.listdir(photoPath):
    if photos.endswith(".jpg"):
        choice = random.choice(photos)
        print(choice)

输出:

J
B
p
_
g
O
C
K
j
.
.
_
_
L
_
_
D
.
g
_
j
E
N
_
.
E
F
.
g
F
_
_
_
g
j
K
g
_
.
_
j
p
.
.
p

2 个答案:

答案 0 :(得分:0)

os.listdir(photoPath)会为您返回一张照片列表,因此如果您想随机选择一张照片,请使用random.choice(os.listdir(photoPath))。从您的代码中,photos仅仅是该照片的名称,而不是整个照片列表。

答案 1 :(得分:0)

让我们一步一步:

# A loop where photos is a filename
for photos in os.listdir(photoPath):
    # Check if photos ends with '.jpg'
    if photos.endswith(".jpg"):
        # Choose a random letter from photos
        choice = random.choice(photos)
        # Print that letter
        print(choice)

执行此操作的正确方法是使用列表解析:

print(random.choice([photos for photos in os.listdir(photoPath) if photos.endswith(".jpg")]))
相关问题