어썸한 문법 제보 받습니다.
def add(a, b, c):
return a + b * c
nums = [1, 2, 3]
result = add(*numbers)
print(result) # output: 7
arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
arr = [*arr1, *arr2]
print(arr) # output: [1, 2, 3, 4, 5, 6]
tup1 = (1, 2, 3)
tup2 = (4, 5, 6)
tup = (*tup1, *tup2)
print(tup) # 출력: (1, 2, 3, 4, 5, 6)
def print_info(name, age, city):
print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")
person = {"name": "John", "age": 30, "city": "New York"}
print_info(**person)
# output
# Name: John
# Age: 30
# City: New York
x = {'Alice' : 18}
y = {'Bob' : 27, 'Ann' : 22}
z = {**x,**y} # {'Alice': 18, 'Bob': 27, 'Ann': 22}
# python 3.9부터는 다음 방식도 가능
z = x | y
origin_lst = [[1, 2], [3, 4], [5, 6]]
flatten_lst = []
for sub_lst in origin_lst:
for item in sub_lst:
flatten_lst.append(item)
print(flatten_lst) # output: [1, 2, 3, 4, 5, 6]
origin_lst = [[1, 2], [3, 4], [5, 6]]
flatten_lst = [item for sub_lst in origin_lst for item in sub_lst]
print(flatten_lst) # output: [1, 2, 3, 4, 5, 6]
from itertools import chain
origin_lst = [[1, 2], [3, 4], [5, 6]]
flatten_lst = list(chain(*origin_lst))
print(flatten_lst) # output: [1, 2, 3, 4, 5, 6]
names = ["Alice", "Bob", "Charlie"]
ages = [28, 25, 32]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")
# output
# Alice is 28 years old.
# Bob is 25 years old.
# Charlie is 32 years old.
keys = ["name", "age", "city"]
values = ["John", 30, "New York"]
merged_dict = dict(zip(keys, values))
print(merged_dict) # output: {'name': 'John', 'age': 30, 'city': 'New York'}
list1 = [1, 2, 3, 4, 5]
list2 = [5, 4, 3, 2, 1]
comparison = [a == b for a, b in zip(list1, list2)]
print(comparison) # output: [False, False, True, False, False]
fruits = ["apple", "banana", "grape"]
for fruit in fruits:
if fruit == "pineapple":
print("Found pineapple!")
break
else:
print("Pineapple not found.")
# output
# Pineapple not found.
n = 10
while n > 0:
n -= 1
if n == 5:
print("Break at 5")
break
else:
print("Loop finished.")
# output
# Break at 5
squares = [x ** 2 for x in range(1, 6)]
print(squares) # output: [1, 4, 9, 16, 25]
even_numbers = [x for x in range(1, 11) if x % 2 == 0]
print(even_numbers) # output: [2, 4, 6, 8, 10]
fruits = ["apple", "banana", "grape"]
for fruit in reversed(fruits):
print(fruit)
# output
# grape
# banana
# apple
numbers = [1, 3, 5, 8, 10]
result = any(x % 2 == 0 for x in numbers)
print(result) # output: True
numbers = [1, 3, 5, 7, 9]
result = all(x % 2 != 0 for x in numbers)
print(result) # output: True
lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(lst[::-1])
# [[7, 8, 9],
# [4, 5, 6],
# [1, 2, 3]]
def rotate(arr):
return list(zip(*arr[::-1]))
print(rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
# [(7, 4, 1),
# (8, 5, 2),
# (9, 6, 3)]