Can you shorten it more simply?

Asked 2 years ago, Updated 2 years ago, 12 views

import json
with open('C:\BicData\camping.json',encoding = 'utf-8') as k:
    data = json.load(k)
i = 0
for camping in data['records']:
    If 'car camping site' in camping ['camping site classification']:
        i += 1
print('A car campsite located across the country is a gun',i', dog.')

I did simple coding using json, but I just came across python I don't know how to make it simpler. Please help me if you can make it shorter.

python

2022-09-21 21:30

3 Answers

It's a shortened version of the code.

import json
with open('C:\BicData\camping.json',encoding = 'utf-8') as k:
    data = json.load(k)


i = len (list(filter('car camping site' in item['camping site'], data['records'])))
print('There are a total of {} car campsites located across the country.'format(i))


2022-09-21 21:30

You have to look at camping.json, but if you use len(), you can see the data length, and you don't have to use i+=1 and for loop.


2022-09-21 21:30

You can also reduce it like this.

import json
with open('C:\BicData\camping.json',encoding = 'utf-8') as k:
    data = json.load(k)

i = len ([c for c in data['records'] if 'car campsite' in c['camping site classification'])
print('There are a total of {} car campsites located across the country.'format(i))


2022-09-21 21:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.