簡體   English   中英

打印由包含變量名的列表給出的列表的內容

[英]Print the contents of a list given by list containing the variable name

我覺得標題不是最好的,所以希望我能正確解釋它。

我有一個列表,其中包含 output 所需的變量的名稱和順序。

outVar = ['a', 'b', 'c']

但它可能包含不同的變量或以不同的順序

outVar = ['d', 'a', 'c', 'e', 'h', 'f']

列表中命名的變量具有值。 例如:

a = 12

我想遍歷outVar並打印變量的內容。 我以為我可以這樣做:

for i in range(len(outVar):
    print(outVar[i])  

但這只是打印變量的名稱。 例如a ,我想要12

您可以使用 function locals()訪問 scope ,這將返回一個包含所有局部變量的dict

local_scope = locals()

for name in outVar:
    print(name, local_scope[name]) 

您可以使用dict代替,例如

outVar = {'a': 12, 'b': 8, ...}

並將您的循環更改為

for i in outVar.keys():
    print(outVar[i])

在您的列表中,您使用“a”將變量添加為字符或字符串。 只需刪除列表中變量名稱周圍的“”,例如: outVar = [a, b, c]

我不知道你是否期待這個,但我仍然會嘗試一下

outVar = ['d', 'a', 'c', 'e', 'h', 'f']
d = {'a':12}
[d.get(i,i) for i in outVar]

暫無
暫無

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

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