我正在嘗試使用此處的程式將復制和粘貼的串列從 excel 轉換為我可以在 Python 中使用連接操作的串列。當我輸入多個列/行值時,我得到一個我無法操作的串列。請參閱以下示例:
- 該程式如下:
def detail_input():
try:
while True:
data=raw_input()
if not data: break
yield data
except KeyboardInterrupt:
return
- 原始輸入從 excel 復制到 unix 命令列:
123 56
321 42
987 24
- 然后我得到一個看起來像這樣的回報:
userInput = list(detail_input())
[['123\t56'],['321\t42'],['987\t24']]
- 我想要的輸出如下所示:
該組為 123,其個人資料為 56
該組為 321,其個人資料為 42
該組為 987,其個人資料為 24
我嘗試使用以下內容洗掉制表符分隔符:
values = list(csv.reader(userInput, delimiter='\t'))
- 但它將串列轉換為元組,我無法提取單個值 - 我只能提取每個括號內的兩個值:\
[['123','56'],['321','42'],['987','24']]
如果您有任何想法,請幫助
uj5u.com熱心網友回復:
你可以這樣做。
values = list(csv.reader(userInput, delimiter='\t'))
# add the following line to print what you need.
[print("the group is {} and their profile is {}".format(each[0], each[1])) for each in values]
或者像下面這樣簡單的事情。
values = list(csv.reader(userInput, delimiter='\t'))
for each in values:
group = each[0]
profile = each[1]
print("the group is {} and their profile is {}".format(group,profile))
uj5u.com熱心網友回復:
如果格式穩定(總是像\d \t\d ,所以是數字,然后是制表符,然后是另一個數字),您可以執行以下操作
values = {sub_list[0].split('\t')[0]: sub_list[0].split('\t')[1] for sub_list in userInput}
得到一本字典
然后像
for key, value in values.items():
print(f'the group is {key} and their profile is {value}')
但是這種方法不是一個好的開始,你可能會更好地從 excel 匯出 csv 或 tsv 檔案并使用 csv 庫讀取資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/391225.html
上一篇:預期檔案結束
