2019年4月1日月曜日

python basic

x = 3
y = 4
z = 5

x, y, z = 3, 4, 5

my_height = 58

x = int(4.7)   # x is now an integer 4
y = float(4)   # y is now a float of 4.0
>>> print(type(x))
int
>>> print(type(y))
float

String

>>> first_word = 'Hello'
>>> second_word = 'There'
>>> print(first_word + second_word)

HelloThere

>>> print(first_word + ' ' + second_word)

Hello There

>>> print(first_word * 5)

HelloHelloHelloHelloHello

>>> print(len(first_word))

5

>>> first_word[0]

H

>>> first_word[1]

e

print("Mohammed has {} balloons".format(27))
# Mohammed has 27 balloons

new_str = "The cow jumped over the moon."
new_str.split()
# ['The', 'cow', 'jumped', 'over', 'the', 'moon.']

new_str.split(' ', 3)
# maxsplit is set to 3, ['The', 'cow', 'jumped', 'over the moon.']

List

list_of_random_things = [1, 3.4, 'a string', True]
>>> list_of_random_things[-1]
True
>>> list_of_random_things[-2]
a string

When using slicing, it is important to remember that the lower index is inclusive and the upper index is exclusive.

>>> 'isa' in 'this is a string'
False
>>> 5 not in [1, 2, 3, 4, 6]
True

name = "-".join(["García", "O'Kelly"])
print(name)
# García-O'Kelly

letters = ['a', 'b', 'c', 'd']
letters.append('z')
print(letters)
# ['a', 'b', 'c', 'd', 'z']

tuple

location = (13.4125, 103.866667)
print("Latitude:", location[0])
print("Longitude:", location[1])

dimensions = 52, 40, 100
length, width, height = dimensions
print("The dimensions are {} x {} x {}".format(length, width, height))

set

A set is a data type for mutable unordered collections of unique elements.
numbers = [1, 2, 6, 3, 1, 1, 6]
unique_nums = set(numbers)
print(unique_nums)
# {1, 2, 3, 6}

fruit = {"apple", "banana", "orange", "grapefruit"}  # define a set
print("watermelon" in fruit)  # check for element
fruit.add("watermelon")  # add an element
print(fruit.pop())  # remove a random element

dictionary

elements = {"hydrogen": 1, "helium": 2, "carbon": 6}
print(elements["helium"])  # print the value mapped to "helium"
elements["lithium"] = 3  # insert "lithium" with a value of 3 into the dictionary

We can check whether a value is in a dictionary the same way we check whether a value is in a list or set with the in keyword. Dicts have a related method that's also useful, get. get looks up values in a dictionary, but unlike square brackets, get returns None (or a default value of your choice) if the key isn't found.

print("carbon" in elements)
print(elements.get("dilithium"))

Zip

a = [1, 2, 3, 4, 5]
b = [10, 11, 12, 13, 14]
list(zip(a, b)) #[(1, 10), (2, 11), (3, 12), (4, 13), (5, 14)]