Tuples, unlike lists, are immutable. Therefore, it is not possible to add, delete, or change elements after defining a tuple.
The tuple is defined by a comma that passes through the value. It is customary to enclose the entire value in () because using () does not cause an error.
#You can use tuples to assign multiple variables at once.
>>> marx_tuple = ("Groucho","Choico","Harpo")
>>> marx_tuple
('Groucho', 'Choico', 'Harpo')
>>> a,b,c=marx_tuple
>>> a
'Groucho'
>>> b
'Choico'
>>> c
'Harpo'
>>> password = "aaaa"
>>> icecream = "bbbb"
>>> password,icecream =icecream,password
>>> password
'bbbb'
>>> icecream
'aaaa'
#Variable function tuple()You can use to create tuples from others.
>>> marx_list=["Groucho","Choico", 'Haapo']
>>> tuple(marx_list)
('Groucho', 'Choico', 'Haapo')
Features of tuples --Tuples consume less space --Tuples can be used as dictionary keys --There is no risk of accidentally rewriting tuple elements --Named tuples can be used as a simple substitute for objects --Function arguments are passed as tuples.
Dictionaries are similar to lists but do not use offsets such as 0 or 1 when selecting elements because the order of the elements is not controlled. Instead, give each value a ** unique key **. The key can be any immutable type.
To create a dictionary, separate key: value pairs with commas and enclose them in {}.
>>> empty_dict ={}
>>> empty_dict
{}
>>> bierce ={
... "day":"A period of twenty-four hours,mostly misspent",
... "positive":"Mistaken at the top of one's voice",
... "misfortune":"The kind of fortune tha never misses",
... }
>>> bierce
{'day': 'A period of twenty-four hours,mostly misspent', 'positive': "Mistaken at the top of one's voice", 'misfortune': 'The kind of fortune tha never misses'}
You can use the dict () function to convert a sequence of two values into a dictionary. The first element of the sequence is the key and the second element is the value.
#List of two-element tuples
>>> lol = [["a","b"],["c","d"],["e","f"]]
>>> dict(lol)
{'a': 'b', 'c': 'd', 'e': 'f'}
>>> lol = [("a","b"),("c","d"),("e","f")]
#Tuple of a two-element list
>>> dict(lol)
{'a': 'b', 'c': 'd', 'e': 'f'}
>>> lol = (["a","b"],["c","d"],["e","f"])
>>> dict(lol)
{'a': 'b', 'c': 'd', 'e': 'f'}
#List of two-letter strings
>>> los = ["ab","cd","ef"]
>>> dict(los)
{'a': 'b', 'c': 'd', 'e': 'f'}
#Two-letter string tuple
>>> los = ("ab","cd","ef")
>>> dict(los)
{'a': 'b', 'c': 'd', 'e': 'f'}
Use the key to refer to the element and assign the value. If the key already exists in the dictionary, the existing value will be replaced with the new value. ** If the key does not already exist, it will be added to the dictionary along with the value. ** **
#The key does not exist and is added to the dictionary as a set of keys and values
#Replace the value because the key already exists
>>> pythons
{'Chapman': 'Graham', 'Takada': 'Takashi', 'Atushi': 'Kataoka', 'Palin': 'Michael'}
>>> pythons["Gilliam"] = "Gerry"
>>> pythons
{'Chapman': 'Graham', 'Takada': 'Takashi', 'Atushi': 'Kataoka', 'Palin': 'Michael', 'Gilliam': 'Gerry'}
#If multiple keys are used, the last value remains.
>>> pythons["Gilliam"] = "Terry"
>>> pythons
{'Chapman': 'Graham', 'Takada': 'Takashi', 'Atushi': 'Kataoka', 'Palin': 'Michael', 'Gilliam': 'Terry'}
#"Chapman"To the key"Graham"After substituting"Tatuo"Is replaced with.
>>> some_pythons = {
... "Chapman":"Graham",
... "Takada":"Takashi",
... "Palin":"Michael",
... "Chapman":"Tatuo",
... }
>>> some_pythons
{'Chapman': 'Tatuo', 'Takada': 'Takashi', 'Palin': 'Michael'}
You can use the update () function to copy a dictionary key and value to another dictionary.
>>> pythons = {
... "Chapman":"Graham",
... "Takada":"Takashi",
... "Palin":"Michael",
... "Atushi":"Kataoka",
... }
>>> pythons
{'Chapman': 'Graham', 'Takada': 'Takashi', 'Palin': 'Michael', 'Atushi': 'Kataoka'}
#If the second dictionary has the same keys contained in the first dictionary, the values in the second dictionary remain.
>>> others = {"Marx":"Gerge",'Takada': 'Takakakakakkakka'}
>>> pythons.update(others)
>>> pythons
{'Chapman': 'Graham', 'Takada': 'Takakakakakkakka', 'Palin': 'Michael', 'Atushi': 'Kataoka', 'Marx': 'Gerge', 'Howard': 'Moe'}
>>> del pythons["Marx"]
>>> pythons
{'Chapman': 'Graham', 'Takada': 'Takakakakakkakka', 'Palin': 'Michael', 'Atushi': 'Kataoka', 'Howard': 'Moe'}
To remove all keys and values from the dictionary, use clear () or substitute an empty dictionary {} for the dictionary name.
>>> pythons.clear()
>>> pythons
{}
>>> pythons = {}
>>> pythons
{}
>>> pythons = {'Chapman': 'Graham', 'Takada': 'Takashi', 'Palin': 'Michael', 'Atushi': 'Kataoka', 'Marx': 'Gerge', 'Howard': 'Moe'}
#"key" in "Dictionary name"Grammar
>>> "Chapman" in pythons
True
>>> "Chaaaaan" in pythons
False
Specify the dictionary and key to retrieve the corresponding value.
>>> pythons = {'Chapman': 'Graham', 'Takada': 'Takashi', 'Palin': 'Michael', 'Atushi': 'Kataoka', 'Marx': 'Gerge', 'Howard': 'Moe'}
>>> pythons["Howard"]
'Moe'
#Exception occurs if the key is not in the dictionary
>>> pythons["Howaaa"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Howaaa'
#3 ways to check if the key exists in advance to avoid exceptions
#use in
>>> "Howaaa" in pythons
False
#Get for dictionary only()Use functions Pass dictionaries, keys, option values
#Returns the value of the key, if any
>>> pythons.get("Marx")
'Gerge'
#If there is no key, the specified option value is returned.(Second argument)
>>> pythons.get("Howaaa","Not a Python")
'Not a Python'
#If you don't make an option, it will be None
>>> pythons.get("Howaaa")
You can get all the keys in the dictionary using keys (). In Python3, you also need to use the list () function when you want the return values of values () and items () to be regular Python lists.
>>> signals = {"green":"go","yellow":"go faster","red":"smile for the camera"}
#Get all the keys in the dictionary
>>> signals.keys()
dict_keys(['green', 'yellow', 'red'])
#To get all the values in the dictionary values()use
>>> list(signals.values())
['go', 'go faster', 'smile for the camera']
#All keys from the dictionary/If you want to retrieve value pairs, items()Use a function
>>> list(signals.items())
[('green', 'go'), ('yellow', 'go faster'), ('red', 'smile for the camera')]
As with lists, making changes to a dictionary affects all names that reference that dictionary.
#save_Affected because signals also refer to the same object
>>> signals = {"green":"go","yellow":"go faster","red":"smile for the camera"}
>>> save_signals = signals
>>> signals["blue"]="confuse everyone"
>>> save_signals
{'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera', 'blue': 'confuse everyone'}
>>> signals
{'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera', 'blue': 'confuse everyone'}
#Key to another dictionary/If you want to copy the value copy()use.
>>> signals = {"green":"go","yellow":"go faster","red":"smile for the camera"}
>>> original_signals = signals.copy()
>>> signals["blue"]="confuse everyone"
>>> signals
{'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera', 'blue': 'confuse everyone'}
#Unaffected
>>> original_signals
{'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}
A set is like a dictionary that throws out values and leaves only the keys. Use a dictionary if you want to add a value to a key.
To create a set, use the set () function, or enclose one or more comma-separated values in {} and assign them.
#An empty set is a set with no elements
>>> empty_set = set()
>>> empty_set
set()
>>> even_numbers = {0,2,4,6,8}
>>> even_numbers
{0, 2, 4, 6, 8}
You can create a set by removing duplicate values from lists, strings, tuples, and dictionaries.
#"t","e"Are duplicated, but the set contains only one.
>>> set("letters")
{'l', 's', 't', 'r', 'e'}
#Create a set from a list
>>> set(["Danger","Dancer","Prancer","Mason-Dixon"])
{'Mason-Dixon', 'Danger', 'Prancer', 'Dancer'}
#Create a set from tuples
>>> set(("Ummaguma","Echoes","Atom Heart Mother"))
{'Echoes', 'Ummaguma', 'Atom Heart Mother'}
#set()If you pass the dictionary to, only the key will be used.
>>> set({'apple':"red", 'orange':"orange", 'cherry':"red"})
{'apple', 'orange', 'cherry'}
#Both sets and dictionaries{}Although it is surrounded by, the set is just a sequence, while the dictionary is key:It is a sequence of value pairs.
>>> drinks = {
... "martini":{"vodka","vermouth"},
... "black russian":{"vodka","kahlua"},
... "manhattan":{"cream","kahlua","vodka"},
... "white russian":{"rye","vermouth","bitters"},
... "screwdriver":{"orange juice","vodka"}
... }
#Key from the dictionary drinks/Take out the pair of value in order, each name/Assign to contents and to contents"vodka"The value of the key including is output.
>>> for name,contents in drinks.items():
... if "vodka" in contents:
... print(name)
...
martini
black russian
manhattan
screwdriver
#Key from the dictionary drinks/Take out the pair of value in order, each name/Assign to contents and to contents"vodka"Including"vermouth"Or"cream"The value of the key that does not include is output.
>>> for name,contents in drinks.items():
... if "vodka" in contents and not ("vermouth" in contents or
... "cream" in contents):
... print(name)
...
black russian
screwdriver
The result of the & operator is a set that contains all the elements contained in both sets.
#to contents"vermouth"、"orange juice"If both are not included&The operator is the empty set{}return it.
>>> for name,contents in drinks.items():
... if contents & {"vermouth","orange juice"}:
... print(name)
...
martini
white russian
screwdriver
#3.5.3 Code rewriting at the bottom
>>> for name,contents in drinks.items():
... if "vodka" in contents and not contents & {"vermouth","cream"}:
... print(name)
...
black russian
screwdriver
#Let's look at all set operators
>>> bruss = drinks["black russian"]
>>> wruss = drinks["white russian"]
>>> a={1,2}
>>> b={2,3}
#Intersection:&Or intersection()Use a function
>>> a & b
{2}
>>> a.intersection(b)
{2}
>>> bruss & wruss
set()
#Union:|Or union()Use a function
>>> a | b
{1, 2, 3}
>>> a.union(b)
{1, 2, 3}
>>> bruss | wruss
{'cream', 'kahlua', 'vodka'}
#Difference set:-Or difference()Use a function.(A set of elements that are included in the first set but not in the second set)
>>> a-b
{1}
>>> a.difference(b)
{1}
>>> bruss-wruss
set()
>>> wruss-bruss
{'cream'}
#Exclusive OR:^Or symmetric_difference()Use a function (elements contained in either)
>>> a ^ b
{1, 3}
>>> a.symmetric_difference(b)
{1, 3}
>>> bruss^wruss
{'cream'}
#Subset:<=Or issubset()use.
>>> a <=b
False
>>> a.issubset(b)
False
>>> bruss<=wruss
True
#Every set is a subset of itself.
>>> a<=a
True
>>> a.issubset(a)
True
#Whether the first set is a true subset of the second set.
#The second set must have another element in addition to all the elements of the first set.<Can be calculated with.
>>> a < b
False
>>> a<a
False
>>> bruss<wruss
True
#Superset: A relationship in which all elements of the second set are also elements of the first set, which is the opposite of the subset.
# >=Or is superset()Check with a function.
>>> a>=b
False
>>> a.issubset(b)
False
>>> wruss >= bruss
True
#All sets are supersets of themselves.
>>> a>=a
True
>>> a.issuperset(a)
True
#True superset: Whether the first set contains all the elements of the second set and other elements
>>> a > b
False
>>> wruss > bruss
True
#The set is not a direct superset of itself
>>> a>a
False
--The list is in square brackets [] --Tuples are commas --Dictionaries and sets are {}
Represented by
The reference method is as follows. --For lists and tuples, the numbers in the brackets are offset --For dictionaries, the key
>>> marx_list=["akagi","Takasuka","Syuda"]
>>> marx_tuple="akagi","Takasuka","Syuda"
>>> marx_dict={"akagi","Takasuka","Syuda"}
>>> marx_list=[2]
>>> marx_list=["akagi","Takasuka","Syuda"]
>>> marx_list[2]
'Syuda'
>>> marx_tuple[2]
'Syuda'
>>> marx_dict={"akagi":"banjo","Takasuka":"help","Syuda":"harp"}
>>> marx_dict["Syuda"]
'harp'
>>> marxs=["akagi","Takasuka","Syuda"]
>>> pythons=["Gilliam","Cleese","Gilliam"]
>>> stooges=["Moe","Curly","Larry"]
#Create tuples from individual lists
>>> tuple_of_lists=marxs,pythons,stooges
>>> tuple_of_lists
(['akagi', 'Takasuka', 'Syuda'], ['Gilliam', 'Cleese', 'Gilliam'], ['Moe', 'Curly', 'Larry'])
#Create a list including a list
>>> list_of_lists=[marxs,pythons,stooges]
>>> list_of_lists
[['akagi', 'Takasuka', 'Syuda'], ['Gilliam', 'Cleese', 'Gilliam'], ['Moe', 'Curly', 'Larry']]
#Create a dictionary of lists
#Since dictionary keys must be immutable, lists, dictionaries, and sets cannot be keys for other dictionaries.
>>> dict_of_lists ={"Marxes":marxes,"Pythons":pythons,"Stooges":stooges}
>>> dict_of_lists
{'Marxes': ['Groucho', 'Choico', 'Haapo'], 'Pythons': ['Gilliam', 'Cleese', 'Gilliam'], 'Stooges': ['Moe', 'Curly', 'Larry']}
#Lists, dictionaries, and sets cannot be keys to other dictionaries because dictionary keys must be immutable, but tuples can be keys.
>>> houses={
... (44.79,-43.55,373):"My House"}
>>> years_list=[1994,1995,1996,1997,1998,1999]
#Note that the offset starts at 0
>>> years_list[4]
1998
#offset-The right end can be selected by specifying as 1.
>>> years_list[-1]
1999
>>> things=["mozzarella","cinderella","salmonella"]
>>> things
['mozzarella', 'cinderella', 'salmonella']
#capitalize()Uppercase the first character of the string in the function.
>>> things[1]=things[1].capitalize()
>>> things
['mozzarella', 'Cinderella', 'salmonella']
#upper()Capitalize the element string in the function.
>>> things[2]=things[2].upper()
>>> things
['mozzarella', 'Cinderella', 'SALMONELLA']
#You can delete an element with del
>>> del things[2]
>>> things
['mozzarella', 'Cinderella']
>>> surprize=["Groucho","Chico","Harpo"]
>>> surprize
['Groucho', 'Chico', 'Harpo']
#Make the last string all lowercase.
>>> surprize[2]=surprize[2].lower()
#Substitute the last element in reverse order
>>> surprize[2]=surprize[-1][::-1]
#Uppercase the first letter of the last element.
>>> surprize[2]=surprize[2].capitalize()
>>> surprize[2]
'Oprah'
>>> e2f={"dog":"chien","cat":"chat","walrus":"morse"}
>>> e2f
{'dog': 'chien', 'cat': 'chat', 'walrus': 'morse'}
#Is the key"walrus"To display the value
>>> e2f["walrus"]
'morse'
#Don't forget to initialize f2e
>>> f2e={}
#items()Use to english each key and value,Store in french
>>> for english,french in e2f.items():
... f2e[french] = english
...
>>> f2e
{'chien': 'dog', 'chat': 'cat', 'morse': 'walrus'}
#Is the key"chien"To display the value
>>> f2e["chien"]
'dog'
#Set creation is set()To use.
>>> set(e2f.keys())
{'walrus', 'dog', 'cat'}
>>> life={"animals":{"cats":["Henry","Grumpy","Lucy"],"octpi":{},"emus":{}},"plants":{},"other":{}}
#key()Is used to display the key of the multiple dictionary life
>>> print(life.keys())
dict_keys(['animals', 'plants', 'other'])
#key()Using multiple dictionaries life["animals"]Is displaying the key of
>>> print(life["animals"].keys())
dict_keys(['cats', 'octpi', 'emus'])
#Multiple dictionary life["animals"]["cats"]Is displaying the value of
>>> print(life["animals"]["cats"])
['Henry', 'Grumpy', 'Lucy']
Until now, the comment was written next to the execution statement, but when I looked back, it turned out to be very difficult to see. It's easier to see by writing it above the execution statement, so let's fix the previous one.
"Introduction to Python3 by Bill Lubanovic (published by O'Reilly Japan)"
Recommended Posts