我有一個我想傳遞給一些變數的名稱串列,但是這些變數都有一個唯一的名稱。我正在迭代,因為在這個例子中,變數似乎很少,但在我的真實場景中,寫出并分配一個串列值會很多。
names = ["apple", 1, 50, "boat", 5, 90, "tree", 4, 96]
n1=q1=t1=""
n2=q2=t2=""
n3=q3=t3=""
name = 0
quantity = 1
total = 2
value = len(names)
value = (value // 3) 1
for i in range(1, value):
tempN = "n" str(i)
tempQ = "q" str(i)
tempT = "t" str(i)
# using locals(), when i print the variables, n1, q1, t1...they all end up empty .
# using exec() I get this error, all the examples to solve this error wasn't very helpful
# since most of them had to do with input from the user.
# File "<string>", line 1, in <module>
# NameError: name 'apple' is not defined
locals()[tempN] = names[name]
locals()[tempQ] = names[quantity]
locals()[tempT] = names[total]
exec("%s = %s" % (tempN, names[name]))
exec("%s = %s" % (tempQ, names[quantity]))
exec("%s = %s" % (tempT, names[total]))
name = 3
quantity = 3
total = 3
這有點過于簡單化了,但想法保持不變,我有很多變數需要從串列中獲取值。一切都可以改變,除了串列格式,或者它是一個串列的事實。
有誰知道更好的方法或解決我的問題?
uj5u.com熱心網友回復:
您應該使用 Python 的資料結構,尤其是dictionaries,這通常會導致撰寫的代碼更少,并使您的代碼比使用eval函式更具可讀性。
from collections import defaultdict
result = defaultdict(dict)
keys = ['name', 'quantity', 'total']
names = ["apple", 1, 50, "boat", 5, 90, "tree", 4, 96]
for i, values in enumerate(
[names[x:x len(keys)] for x in range(0, len(names), len(keys))]
):
result[i] = dict(zip(keys, values))
print(result)
出去:
defaultdict(<class 'dict'>,
{0: {'name': 'apple', 'quantity': 1, 'total': 50},
1: {'name': 'boat', 'quantity': 5, 'total': 90},
2: {'name': 'tree', 'quantity': 4, 'total': 96}})
uj5u.com熱心網友回復:
我認為將串列拆分為子串列可以幫助您
list = ["apple", 1, 50, "boat", 5, 90, "tree", 4, 96]
sublists = [list[x:x 3] for x in range(0,len(list),3)]
for element in sublists:
print(element)
輸出
['apple', 1, 50]
['boat', 5, 90]
['tree', 4, 96]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/406587.html
標籤:
