1

forループを使用すると、次のPythonコードが機能します。

for item in results:
    item ['currentservertime'] = int(time.time())

ただし、リスト内包表記でやりたいと思います。だから私は次のことを試しましたが、=で構文エラーが発生します

item['currentservertime'] = int(time.time()) for item in results

どこが間違っているのですか?

4

2 に答える 2

10

リストを作成しているわけではないため、リスト内包表記はここでは機能しません。さまざまな辞書の値を変更しているからです。元のコードが次の形式の場合、リスト内包表記が適切なツールになります。

currentservertime = []
for item in results:
    currentservertime.append(int(time.time())

これはリスト内包に変換されます:

currentservertime = [int(time.time()) for item in results]

現状では、既存のループは、実行していることを実装するための最も明確で直接的な方法です。

于 2012-08-22T01:50:05.720 に答える
0
[i.update({'currentservertime': int(time.time())}) for i in results]
于 2012-08-22T03:07:39.937 に答える