簡體   English   中英

使用 split() 解壓縮 python 中的列表

[英]Unpacking a list in python using split()

import os
os.chdir('/path/to/files/')
for f in os.listdir():
    file_name,file_ext=os.path.splitext(f)
    print(file_name,file,ext)

Output

earth - our solar system - #4 .mp4
pluto - our solar system - #5 .mp4
jupiter - our solar system - #1 .mp4
venus - our solar system - #3 .mp4
mars - our solar system - #2 .mp4

上面的代碼工作得很好,但是當我添加最后兩行代碼時出現錯誤

import os
os.chdir('/Users/malbairmani/Desktop/rt')
for f in os.listdir():

    file_name,file_ext=os.path.splitext(f)
    print(file_name,file_ext)
    x,y,z= file_name.split('-')
    print(x,y,z)

Output:

ValueError: not enough values to unpack (expected 3, got 1)

但是,如果我輸入x=file_spilt('-') ,它工作得很好

即使字符串中沒有'-' ,添加.split('-')也不會返回錯誤,它只會將整個字符串存儲到一個列表中。

暫無
暫無

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

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