def list_chunk(lst, n): 
     return [lst[i:i+n] for i in range(0, len(lst), n)]

list_test = list(range(1,30))
print("분할 전 : ", list_test)

list_chunked = list_chunk(list_test, 6)
print("분할 후 : ", list_chunked) 

 

# 출력

# 분할 전 : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]

# 분할 후 : [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18], [19, 20, 21 22, 23, 24], [25, 26, 27, 28 29, 30],[31]]

'SW > Python' 카테고리의 다른 글

[python] json파일 다루기  (0) 2023.11.02

1. json파일 읽기


import json

with open('C:\\test.json', 'r') as f:

    json_data = json.load(f)

 

 

  - 읽은 json 파일 출력하기

print(json.dumps(json_data) ) 

 print(json.dumps(json_data, indent="\t") ) # align 맞추어 출력하기

  

 

 

 

 2. json 파일 내의 특정 key의 내용만 출력하기

result = json_data['key1']['key2'] # key1의 요소인 key2의 내용을 출력

print(result)

 

 

 

 

 3. json 파일 수정하기

json_data['key1']['key2'] = "7000" # key1의 요소인 key2의 내용을 7000으로 변경

print(json_data['key1']['key2']) # 7000이 출력됨

 

 

 

4. python 코드로 json 파일 저장하기

 

예시

import json

car_group = dict()

k5 = dict()

k5["price"] = "5000"

k5["year"] = "2015"

car_group["K5"] = k5


avante = dict()

avante["price"] = "3000"

avante["year"] = "2014"

car_group["Avante"] = avante



#json 파일로 저장

with open('C:\\test.json', 'w', encoding='utf-8') as make_file:

    json.dump(car_group, make_file, indent="\t")


    

# 저장한 파일 출력하기

with open('C:\\test.json', 'r') as f:

    json_data = json.load(f)

print(json.dumps(json_data, indent="\t") )

 

 

 

 

 - 결과

{
    "K5": {
        "price": "5000",
        "year": "2015"
    },
    "Avante": {
        "price": "3000",
        "year": "2014"
    }
}

 

 

 

 

'SW > Python' 카테고리의 다른 글

[Python] 리스트 분할 split 나누기 자르기  (0) 2023.12.18

+ Recent posts