This is my memo for studying python Check the operation of the sample source with "Google Colaboratory".
test.py
list = []
for i in range(5):
list.append(x)
print(list)
# => [0, 1, 2, 3, 4]
test.py
list = [i for i in range(5)]
print(list)
# => [0, 1, 2, 3, 4]
By adding if, the elements in List will be reduced. ** Supplement ** The if in the comprehension is called the if clause.
test.py
#[For statement] Put only even numbers in the List
list = []
for i in range(10):
if i % 2 == 0:
list.append(i)
print(list)
# => [0, 2, 4, 6, 8]
#[Comprehension notation] Put only even numbers in the List
list = [i for i in range(10) if i % 2 == 0]
print(list)
# => [0, 2, 4, 6, 8]
** Supplement ** If-else in the comprehension is called a conditional expression
test.py
#[For statement] Enter "even" and "odd"
list = []
for i in range(10):
if i % 2 == 0:
list.append("Even")
else:
list.append("Odd")
print(list)
# => ['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd']
#[Comprehension] Enter "even" and "odd"
list = ["Even" if i % 2 == 0 else "Odd" for i in range(10)]
print(list)
# => ['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd']
test.py
dict = {}
key_list = [1, 2, 3]
value_list = ["abc", "def", "xyz"]
for i in range(len(key_list)):
key = key_list[i]
value = value_list[i]
dict[key] = value
print(dict)
# => {1: 'abc', 2: 'def', 3: 'xyz'}
test.py
key_list = [1, 2, 3]
value_list = ["abc", "def", "xyz"]
dict = {key : value for key, value in zip(key_list, value_list)}
print(dict)
# => {1: 'abc', 2: 'def', 3: 'xyz'}
Writing in comprehension will make it much shorter, but it's a little difficult to read until you get used to it.
When writing this When I was writing java as a subcontractor of an SI shop a long time ago, I couldn't read "ternary operator" and it would be shorter, so don't use it (angry) For some reason, I remembered what the prime contractor said.
*** Shortening ** ⇒ As you may know recently, the estimate of step unit price used to be ... (ry)
Thank you to shiracamus for commenting
Recommended Posts