簡體   English   中英

如何通過遍歷字符串在Python中創建對象?

[英]How can I create objects in Python via iterating through a string?

我從這樣的文件中讀取一行:

a b c d e f

有了這個字符串,我想在用戶類中將每個字母變成一個新的“用戶”。 所以我想要的是這樣的:

for character in **the first line of the file**:
    if character != ' '
        user = user(character)

換句話說,我想要“ userA = user(“ a”)”之類的東西,其中user是我定義為接收字符串作為參數的類。

我很難找到一種方法來迭代Python中關於文件的字符串,然后使用結果創建對象。

您不能在作業的左側添加任何內容(您不能以這種方式構造變量名稱)。 您應該使用字典和str.split方法:

users = {} # note the plural, this is not 'user', but 'users'
for name in myString.split():
    users[name] = user(name)

您還可以使用字典理解來實現相同目的:

users = { name : user(name) for name in myString.split() }

暫無
暫無

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

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