Python can use tuples and dictionaries to express coordinate increases and decreases. The specific method is:
def change_directions(e): #e表示移动方向,list类型 moves = { "up":(0,1),"down":(0,-1),"right":(1,0),"left":(-1,0)} x,y = (0,0) if e: for v in e: dx,dy = moves[v] x += dx y += dy print((x,y))
Tuple introduction
Python’s tuples are similar to lists, except that the elements of the tuple cannot be modified.
Use parentheses for tuples and square brackets for lists.
Tuple creation is very simple, just add elements in brackets and separate them with commas.
The following example:
tup1 = ('physics', 'chemistry', 1997, 2000) tup2 = (1, 2, 3, 4, 5 ) tup3 = "a", "b", "c", "d"
Create an empty tuple
tup1 = ()
When the tuple contains only one element, you need to add a comma after the element
tup1 = (50,)
element Groups are similar to strings. The subscript index starts from 0 and can be intercepted, combined, etc.
Introduction to Dictionaries
Dictionaries are another mutable container model and can store any type of object.
Each key-value key=>value pair in the dictionary is separated by colon :. Each key-value pair is separated by comma,. The entire dictionary is included in curly braces {}. The format is as follows:
d = {key1 : value1, key2 : value2 }
The key is generally unique. If the last key-value pair is repeated, the previous one will be replaced. The value does not need to be unique.
>>>dict = {'a': 1, 'b': 2, 'b': '3'} >>> dict['b'] '3' >>> dict {'a': 1, 'b': '3'}
The value can be of any data type, but the key must be immutable, such as string, number or tuple.
A simple dictionary example:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
You can also create a dictionary like this:
dict1 = { 'abc': 456 } dict2 = { 'abc': 123, 98.6: 37 }
For more Python-related technical articles, please visit the Python Tutorial column Get studying!
The above is the detailed content of How to express coordinates in python. For more information, please follow other related articles on the PHP Chinese website!