亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用“python -c”控制臺命令模式實現for循環

使用“python -c”控制臺命令模式實現for循環

慕容3067478 2024-01-27 14:55:12
我想python -c通過 shell 腳本運行以下代碼:import json,sysobj=json.loads(open('/temp/209/209formatted_response.json','r').read())revision=obj['component']['referencingComponents'][0]['revision']for element in list(revision):    if 'lastModifier' in element:        del revision['lastModifier']print(revision)使用python -c,它在沒有 for 循環的情況下運行良好,但如果我在其中包含 for 循環,它會拋出錯誤:下面工作正常:python -c "import json,sys; obj=json.loads(open('/temp/209/209formatted_response.json','r').read());revision=obj['component']['referencingComponents'][0]['revision']"下面給出錯誤:$ /opt/app/anaconda3/envs/anaconda3/bin/python -c "import json,sys; obj=json.loads(open('/temp/209/209formatted_response.json','r').read());revision=obj['component']['referencingComponents'][0]['revision'];for element in list(revision):    if 'lastModifier' in element:        del revision['lastModifier']; print(revision)"  File "<string>", line 1    import json,sys; obj=json.loads(open('/temp/209/209formatted_response.json','r').read());revision=obj['component']['referencingComponents'][0]['revision'];for element in list(revision):    if 'lastModifier' in element:        del revision['lastModifier']; print(revision)                                                                                                                                                                                      ^SyntaxError: invalid syntax我什至嘗試在行尾的\n循環的每個語句之前使用,但沒有成功;
查看完整描述

2 回答

?
GCT1015

TA貢獻1827條經驗 獲得超4個贊

一種可能的解決方案是使用換行符,但不要直接添加它們:


$ python3 -c "exec(\"n = 3\nfor i in range(n):\n  print(i)\")"

0

1

2

像您一樣添加\n,但也將代碼括起來"exec(\"...\")"


或者您可以插入真正的換行符:


$ python3 -c "n = 3

> for i in range(n):

>   print(i)"

0

1

2


查看完整回答
反對 回復 2024-01-27
?
慕碼人8056858

TA貢獻1803條經驗 獲得超6個贊

問題在于縮進,因此您可以使用過濾函數來代替使用 for 和 if 語句

revision = list(filter(lambda x: not 'lastModifier' in x, list(revision)));


查看完整回答
反對 回復 2024-01-27
  • 2 回答
  • 0 關注
  • 266 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號