组合多个列表(Python)

2024-06-16 10:34:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试以选定的格式组合多个列表。简单地说,试图创造 elapsed + "' " + player + ' (A: ' + assist + ') - ' + detail(例如:51' H. Onyekuru (A: R. Babel) - Normal Goal)。我还添加了获取数据的json文件。也许不需要创建列表就可以直接创建它

代码:

elapsed = []
player = []
assist = []
detail = []

for item in data['response']:
        player.append(item['player']['name'])

for item in data['response']:
        elapsed.append(item['time']['elapsed'])

for item in data['response']:
        assist.append(item['assist']['name'])

for item in data['response']:
        detail.append(item['detail'])

JSON文件:

{
  "get": "fixtures/events",
  "parameters": { "fixture": "599120", "type": "goal" },
  "errors": [],
  "results": 3,
  "paging": { "current": 1, "total": 1 },
  "response": [
    {
      "time": { "elapsed": 51, "extra": null },
      "team": {
        "id": 645,
        "name": "Galatasaray",
        "logo": "https://media.api-sports.io/football/teams/645.png"
      },
      "player": { "id": 456, "name": "H. Onyekuru" },
      "assist": { "id": 19034, "name": "R. Babel" },
      "type": "Goal",
      "detail": "Normal Goal",
      "comments": null
    },
    {
      "time": { "elapsed": 79, "extra": null },
      "team": {
        "id": 645,
        "name": "Galatasaray",
        "logo": "https://media.api-sports.io/football/teams/645.png"
      },
      "player": { "id": 456, "name": "H. Onyekuru" },
      "assist": { "id": 142959, "name": "K. Akturkoglu" },
      "type": "Goal",
      "detail": "Normal Goal",
      "comments": null
    },
    {
      "time": { "elapsed": 90, "extra": 7 },
      "team": {
        "id": 3573,
        "name": "Gazi\u015fehir Gaziantep",
        "logo": "https://media.api-sports.io/football/teams/3573.png"
      },
      "player": { "id": 25921, "name": "A. Maxim" },
      "assist": { "id": null, "name": null },
      "type": "Goal",
      "detail": "Penalty",
      "comments": null
    }
  ]
}

输出:

['H. Onyekuru', 'H. Onyekuru', 'A. Maxim']
[51, 79, 90]
['R. Babel', 'K. Akturkoglu', None]
['Normal Goal', 'Normal Goal', 'Penalty']

Tags: nameinidfordataresponseitemnull
2条回答

这将以所需的格式创建字符串列表。作为奖励,python对于iterables来说非常好,所以它可以在一行中完成

list_of_all = [f"{item['time']['elapsed']}' {item['player']['name']} ({item['assist']['name']}) {item['detail']}" for item in data['response']]

当然可以–只需迭代事件并打印出这些行(例如,如果愿意,也可以将它们收集到一个列表中)。下面的f-string语法需要Python 3.6或更高版本

data = {
  # ... elided for brevity, see OP's post
}
for event in data["response"]:
  print(f"{event['time']['elapsed']}' {event['player']['name']} (A: {event['assist']['name']}) {event['detail']}")

这是打印出来的

51' H. Onyekuru (A: R. Babel) Normal Goal
79' H. Onyekuru (A: K. Akturkoglu) Normal Goal
90' A. Maxim (A: None) Penalty

相关问题 更多 >