简体   繁体   中英

How to add multiple values to tabulate array from a range

x = range(98)
for i in x:
    numbers = "{:,}".format(r1["auctions"][(i)]["current_bid"])
    table = [['Title', 'Description', 'Mileage', 'Current Bid'], [r1["auctions"][(i)]["title"], r1["auctions"][(i)]["sub_title"], r1["auctions"][(i)]["mileage"], numbers]]
    print(tabulate(table, headers='firstrow', tablefmt='fancy_grid'))

So current it will print (i)(98) individually but I want all values printed in the same array instead of looping through the range with 1 single data line printed

You should do:

  • before loop you should create list with headers,
  • inside loop you should append() rows to this list
  • after loop you should print all as one table

And you could learn to use for -loop without range()

# --- before loop ---

table = [
    ['Title', 'Description', 'Mileage', 'Current Bid']
]

# --- loop ---

for item in r1['auctions'][:98]:
    row = [
        item['title'],
        item['sub_title'],
        item['mileage'],
        '{:,}'.format(item['current_bid']),
    ]
    table.append(row)
    
# --- after loop ---

print(tabulate(table, headers='firstrow', tablefmt='fancy_grid'))

EDIT:

If you have nested data then you need nested for -loops

Minimal code with some random data.

# --- generate random data ---

import random
import json

random.seed(0)  # to generate always the same data

data = []

for model in ['Opel', 'Mercedes', 'Fiat']:

    all_items = []

    for i in range(3):
        item = {
            'title': model,
            'sub_title': random.choice(['Red', 'Green', 'Blue', 'White', 'Black']),
            'mileage': random.randrange(0, 100),
            'current_bid': random.randrange(1000, 10000),
        }
        all_items.append(item)

    data.append({'auctions': all_items})

print(json.dumps(data, indent=2))

# ----------------------------------

from tabulate import tabulate


# --- before loop ---

table = [
    ['Title', 'Description', 'Mileage', 'Current Bid']
]

# --- loop ---

for model in data:

    for item in model['auctions'][:98]:
        row = [
            item['title'],
            item['sub_title'],
            item['mileage'],
            '{:,}'.format(item['current_bid']),
        ]
        table.append(row)

# --- after loop ---

print(tabulate(table, headers='firstrow', tablefmt='fancy_grid', colalign=['left', 'left', 'right', 'right']))

Result:

[
  {
    "auctions": [
      {
        "title": "Opel",
        "sub_title": "White",
        "mileage": 97,
        "current_bid": 7890
      },
      {
        "title": "Opel",
        "sub_title": "Red",
        "mileage": 33,
        "current_bid": 9376
      },
      {
        "title": "Opel",
        "sub_title": "White",
        "mileage": 51,
        "current_bid": 5969
      }
    ]
  },
  {
    "auctions": [
      {
        "title": "Mercedes",
        "sub_title": "White",
        "mileage": 45,
        "current_bid": 4578
      },
      {
        "title": "Mercedes",
        "sub_title": "Black",
        "mileage": 17,
        "current_bid": 5617
      },
      {
        "title": "Mercedes",
        "sub_title": "Green",
        "mileage": 96,
        "current_bid": 2553
      }
    ]
  },
  {
    "auctions": [
      {
        "title": "Fiat",
        "sub_title": "Black",
        "mileage": 32,
        "current_bid": 9725
      },
      {
        "title": "Fiat",
        "sub_title": "Black",
        "mileage": 18,
        "current_bid": 6081
      },
      {
        "title": "Fiat",
        "sub_title": "Red",
        "mileage": 93,
        "current_bid": 2208
      }
    ]
  }
]
╒══════════╤═══════════════╤═══════════╤═══════════════╕
│ Title    │ Description   │   Mileage │   Current Bid │
╞══════════╪═══════════════╪═══════════╪═══════════════╡
│ Opel     │ White         │        97 │         7,890 │
├──────────┼───────────────┼───────────┼───────────────┤
│ Opel     │ Red           │        33 │         9,376 │
├──────────┼───────────────┼───────────┼───────────────┤
│ Opel     │ White         │        51 │         5,969 │
├──────────┼───────────────┼───────────┼───────────────┤
│ Mercedes │ White         │        45 │         4,578 │
├──────────┼───────────────┼───────────┼───────────────┤
│ Mercedes │ Black         │        17 │         5,617 │
├──────────┼───────────────┼───────────┼───────────────┤
│ Mercedes │ Green         │        96 │         2,553 │
├──────────┼───────────────┼───────────┼───────────────┤
│ Fiat     │ Black         │        32 │         9,725 │
├──────────┼───────────────┼───────────┼───────────────┤
│ Fiat     │ Black         │        18 │         6,081 │
├──────────┼───────────────┼───────────┼───────────────┤
│ Fiat     │ Red           │        93 │         2,208 │
╘══════════╧═══════════════╧═══════════╧═══════════════╛

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM