[英]Reversing a global variable within function -- Python
closes = []
def check_indicator():
global closes
closes.reverse()
print(closes)
connection = psycopg2.connect(
host='localhost',
database='postgres',
user='postgres',
password='pass'
)
connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = connection.cursor()
cur.execute('select closeprice from candles order by datetime desc limit 54')
closes.extend(cur.fetchall())
check_indicator()
運行上面的代碼時,我得到一個未反轉的closes
列表,是什么導致了這種情況的發生? 我已經在 function 中聲明了global closes
。 但是,當我聲明一個依賴於 function 內部closes
的變量時,就像這個reversed_closes = closes.reverse()
一樣,它返回None
您需要制作另一個列表並手動翻轉它; 方法如下:
list_1 = ["Item1", "Item2", "Item3"]
list_2 = []
for i in list_1[::-1]:
list_2.append(i)
print(list_2)
如果你想在 function 中使用它,你可以這樣做:
def rev_list(list_item): # rev_list and list_item are changable if you like
new_list = []
for i in list_item[::-1]:
new_list.append(i)
return new_list
希望我能幫上忙
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.