Paiza Python Primer 4: List Basics

01 Learn what a list is

A type of data structure. Handles well-known data

lesson.py


Array=list

Variable "one by one"

Variable player_1="Brave"
Variable player_2="Wizard"

list[There are multiple]

team[0]="Brave"
team[1]="Wizard"
team[2]="Dragon"

It starts from 0

Specific example of list

team[0]="Brave"
team[1]="Wizard"
team[2]="Dragon"(Add data)、(Data change)、(Delete data)

Refer to the data by number
print(team[0])

Calculate the number
print(team[n+1])

The number of data
print(len(team)

How to use the list
1.Processing that requires order management
・ Attendance number, seating order, party order
・ Game data such as playing cards and shogi
2.Web form choices
.Age, prefecture, etc.
3.Multi-line data like excel
・ CSV data processing

02: Let's make a list

lesson.py



#variable
player_1="Brave"
player_2="Wizard"

print(player_1)
print(player_2)

#list
team = ["Brave","Wizard",100,player_1]
print(team)

Exercise

lesson.py


list = ["Warrior","samurai","Monk","Wizard"]
#Below this, let's output a list
print(list)


  1. Let's make a list of specified characters

lesson.py


item = ["Long sword","Blade sword","Excalibur"]
print(item)
  1. Let's assign to the list with a variable

lesson.py


#Assign to a list with a variable

player_1 = "Brave"
player_2 = "Wizard"
player_3 = "Warrior"

# player_1 ~Write 3 in the list and output it with the print function.
team=[player_1,player_2,player_3]

print(team)

03: Let's take out the elements of the list

lesson.py


team = ["Brave", "Wizard"]
print(team)
print(team[0])
num=0
print(team[num +1 ])

#An error print(team[10])

#The number of elements can be displayed
print(len(team))

List reference Specify the element number

print(team[0])Specify directly with a numerical value
print(team[num])Specify with a variable
print(team[num + 1])Specify with a formula

len function number of elements
print(len(team))


##Exercise


・ Let's take out the zeroth element of the list


#### **`lesson.py`**
```py


 team = ["Brave", "Warrior", "Samurai", "Ninja", "Wizard"]
# Output the leftmost element of team with the print function
print(team[0])

・ Let's take out a specific element from the list

lesson.py



 team = ["Brave", "Warrior", "Samurai", "Ninja", "Wizard"]
# Print the third element of team with the print function
print(team[2])


#### **`lesson.py`**
```py


weapon = ["Wooden stick", "Iron rod", "Iron sword", "Copper sword", "Stone ax", "Excalibur"]
#Write the code that outputs the number of elements here
print(len(weapon))

04: Let's manipulate the list

lesson.py



team = ["Brave", "Wizard"]
print(team)
print(team[1])
print(len(team))

team.append("Warrior")
print(team)
print(len(team))

team[2]="Dragon"
print(team)
print(len(team))

team.pop(2)
print(team)
print(len(team))

['Brave', 'Wizard']
Wizard
2
['Brave', 'Wizard', 'Warrior']
3
['Brave', 'Wizard', 'Dragon']
3
['Brave', 'Wizard']
2

Exercise

  1. "Let's add an element to the list"

lesson.py


 
 weapon = ["Wooden stick", "Iron rod", "Iron sword", "Copper sword"]
#Write the code to add the element here
weapon.append("Stone ax")

print(weapon)

  1. Let's overwrite the elements of the list

lesson.py


 
 weapon = ["Wooden stick", "Iron rod", "Iron sword", "Rusted sword"]
#Write the code that overwrites the element here

#print(weapon)
weapon.pop(3)
#print(weapon)
weapon.append("Stone ax")
print(weapon)

  1. Let's remove the element from the list

lesson.py



weapon = ["Wooden stick", "Iron rod", "Iron sword", "Copper sword"]
#Write the code to delete the element here
weapon.pop(2)
print(weapon)

05: Let's process the list in a loop

lesson.py


team = ["Brave", "Warrior", "Wizard","Thieves"]
#print(team)
#print(team[0])

'''
for i in range(5):
    print(i)
'''
print("<select name='job'>")
for job in team:
    print("<option>" + job +"<optiin>")
print("</select>")

Exercise

  1. Let's display the contents of the list line by line

lesson.py



enemy = ["Slime", "monster", "zombie", "Dragon", "Devil"]
#Here is the code that displays the elements in a loop
for i in enemy:
    print(i + "Has appeared!")
    
  1. Let's calculate the sum of the elements

lesson.py



numbers = [12, 34, 56, 78, 90]
total = 0
for num in numbers:
	#Here is the code to calculate the total
	total += num

print(total)

06: Let's split the data separated by commas with split

lesson.py



line = input().rstrip().split(",")
print(line)
print(len(line))

for enemy in line:
    print(enemy + "Has appeared!")

Exercise

  1. "Let's divide the character string with commas"

lesson.py


team_str = "Brave,Warrior,Ninja,Wizard"

print(team_str.split(","))

  1. Split comma-separated data with split

lesson.py



str = "One cold rainy day when my father was a little boy he met an old alley cat on his street"
words = str.split(" ")
print(len(words))

  1. Split the URL read from standard input

lesson.py



input

https://paiza.jp/cgc/users/ready

url_str = input().rstrip().split("/")
print(url_str)

['https:', '', 'paiza.jp', 'cgc', 'users', 'ready']

07: Let's store multi-line data in a list

Stores only one line of data

lesson.py


input
The brave was walking in the wilderness

line = input().rstrip()
#line =input Read one line from standard input
#Remove the line feed code at the end of the character string with the rstrip function

output
The brave was walking in the wilderness

line = input().rstrip() print(line)


Store multi-line data in a list


#### **`lesson.py`**
```py

 I want to capture multiple lines

for in

 sys.stdin.readlines function Reads all files and processes line by line

import sys
line = sys.stdin.readlines()


 Therefore

import  sys
for line in sys.stdin.readlines():
 print (line.rstrip ()) # Extract the line feed code at the end of the string

lesson.py



 input
 The brave was walking in the wilderness
 The hero fought the monster
 The hero defeated the monster
 The hero saved the world

import  sys
for line in sys.stdin.readlines():
    print(line.rstrip())



 output
 The brave was walking in the wilderness
 The hero fought the monster
 The hero defeated the monster
 The hero saved the world

detailed explanation

lesson.py



import  sys
for line in sys.stdin.readlines():
# The readlines () variable reads all lines at once from standard input
# If it can be read normally, pass it to the line variable in loop processing and output it with print
    print(line.rstrip())
# Since rstrip cannot be used in the first line of for in, execute it in a for loop
# Read even an empty line and the empty line is also displayed

 input
 The brave was walking in the wilderness
 The hero fought the monster

 The hero saved the world

 output
 The brave was walking in the wilderness
 The hero fought the monster

 The hero saved the world

lesson.py



# Add the read data to the list and display them together after the loop

import  sys
 array = [] # 1. Add an empty list called array outside the loop
for line in sys.stdin.readlines():
 array.append (line.rstrip ()) # 2.Lune.rstrip as an argument
    #print(line.rstrip())

 print (array) # 3.print after the loop

 input


 The brave was walking in the wilderness
 The hero fought the monster
 The hero defeated the monster
 The hero saved the world

 output
 ['The brave was walking in the wilderness',' The brave fought the monster','',' The brave defeated the monster',' The brave saved the world']

# Contains lines from

##Exercise

1.Appeared!Output

lesson.py


 input
 Slime
 monster
 zombie
 Dragon
 Devil

 code
import sys
for line in sys.stdin.readlines():
	msg = line.rstrip()
 print (msg + "appears")

 output
 Slime appeared
 A monster has appeared
 Zombie appeared
 The dragon appeared
 Demon King appeared

2."A appeared B"

lesson.py



 input
 Slime, 30
 Monster, 23
 Zombie, 15
 Dragon, 3
 Demon King, 1

 code
import sys
for line in sys.stdin.readlines():
 # Here, write the code that divides the character string and outputs it.
	enemy = line.rstrip().split(",")
.split
 print (enemy [0] + "is" + enemy [1] + "animal appeared")
# print (enemy [0] + "is" + enemy [1] + "animal appeared")

 output
 30 slimes appeared
 23 monsters appeared
 15 zombies appeared
 Three dragons appeared
 One Demon King appeared

##08:Random lottery using a list

lesson.py



 Last review

line = input().rstrip().split(",")
for enemy in line:
 print (enemy + "appears!")

 input
 Slime, monster, dragon

 output
 A slime has appeared!
 A monster has appeared!
 A dragon has appeared!

lesson.py


line = input().rstrip().split(",")
for enemy in line:
 print (enemy + "appears!")

# Examine the range to make a random number

num=len(line)
print(line)
 print ("enemy is" + str (num) + "animal")

 input
 Slime, monster, dragon

 output
 A slime has appeared!
 A monster has appeared!
 A dragon has appeared!
 3 enemies

lesson.py


import random
# Get one line from standard input
line = input().rstrip()

# Divide by comma and assign to list
janken = line.split(",")

# Assign the number of elements in the list to a variable
num = len(janken)

# Output the contents of the list
print(janken)

# Output randomly selected list elements
print(janken[random.randrange(num)])


#### **`.lessonpy`**

##Import random module import random

line = input().rstrip().split(",") for enemy in line: print(enemy + "Has appeared!")

#Examine the range to make a random number num=len(line) print(line) print("The enemy is" +str(num)+ "Animal")

##Generate a random number → Target of a critical hit attack=random.randrange(num) #print(attack)

##To the number you choose, "A blow of conscience!Is displayed print(line[attack] + "A blow of conscience" + line[attack] +"Defeated")

input Slime,monster,Dragon,Devil

output A slime has appeared! A monster has appeared! A dragon has appeared! The Demon King has appeared! ['Slime', 'monster', 'Dragon', 'Devil'] 4 enemies Defeated the Demon King


## Exercise

 1. Let's make a rock-paper-scissors program


#### **`lesson.py`**
```py


import random
#Get one line from standard input
line = input().rstrip()

#Divide by comma and assign to list
janken = line.split(",")

#Assign the number of elements in the list to a variable
num = len(janken)

#Output the contents of the list
print(janken)

#Output randomly selected list elements
print(janken[random.randrange(num)])

  1. Let's make a fortune

lesson.py



import random
#Get one line from standard input
line = input().rstrip()

#Let's write it all on our own this time!

#Divide by comma and assign to list
omikuji = line.split(",")
##Confirm that the list has been generated
print(omikuji)
#Assign the number of elements in the list to a variable
num = len(omikuji)
#Output the contents of the list
print(omikuji)
#Output randomly selected list elements
print(omikuji[random.randrange(num)])

Recommended Posts

Paiza Python Primer 4: List Basics
Paiza Python Primer 5: Basics of Dictionaries
Paiza Python Primer 1 Learn Programming
Paiza Python Primer 8: Understanding Classes
Paiza Python Primer 7: Understanding Functions
Python basics ⑤
Python basics
Python basics ④
Python basics ③
Python basics
[Python] list
Python basics
Python basics
Python basics ③
Python basics ②
Python basics ②
About the basics list of Python basics
Python basics memorandum
#Python basics (#matplotlib)
Python CGI basics
Basics of Python ①
Basics of python ①
Python slice basics
#Python basics (scope)
#Python basics (#Numpy 1/2)
#Python basics (#Numpy 2/2)
#Python basics (functions)
Python> Comprehension / Comprehension> List comprehension
Python array basics
Python profiling basics
Python #Numpy basics
Python basics: functions
Python list manipulation
#Python basics (class)
Python basics summary
About Python List Index (Paiza POH Lite 4: Mission 3)
Sorted list in Python
Python Exercise 2 --List Comprehension
List of python modules
Python> list> extend () or + =
Python basics ② for statement
Python: Unsupervised Learning: Basics
Basics of Python scraping basics
Python list comprehension speed
Python basics 8 numpy test
python unittest assertXXX list
Errbot: Python chatbot basics
Python3 List / dictionary memo
OpenCV3 Python API list
Python error list (Japanese)
Python basics: Socket, Dnspython
List find in Python
# 4 [python] Basics of functions
Python Tkinter Primer Note
Basics of python: Output
Python exception class list
Initialize list with python
Paiza Python Primer 2: Learn Conditional Branching and Comparison Operators
Python hand play (two-dimensional list)
Python list, for statement, dictionary
Summary of Python3 list operations