Learn Python from Scratch

Educative:Learn Python from Scratch

LIST []
1.Adding a Condition
All the values of the nums list were simply doubled and added to nums_double. if we wanted our new list to have elements which were divisible by 4.

nums = [10, 20, 30, 40, 50]
# List comprehension
nums_double = [n * 2 for n in nums if n % 4 == 0]
print(nums)
print(nums_double)

Output
[10, 20, 30, 40, 50]
[40, 80]
2.Using Multiple Lists
write a list comprehension which creates tuples out of the values in two lists when their sum is greater than 100. These tuples are the elements of the new list.

list1 = [30, 50, 110, 40, 15, 75]
list2 = [10, 60, 20, 50]

sum_list = [(n1, n2) for n1 in list1 for n2 in list2 if n1 + n2 > 100]

print(sum_list)

Output:[(50, 60), (110, 10), (110, 60), (110, 20), (110, 50), (75, 60), (75, 50)]

Tuples ()
A tuple is immutable. However, it can contain mutable elements like a list.
在这里插入图片描述
1.Merging Tuples

hero1 = ("Batman", "Bruce Wayne")
hero2 = ("Wonder Woman", "Diana Prince")
awesome_team = hero1 + hero2
print(awesome_team)

Output
('Batman', 'Bruce Wayne', 'Wonder Woman', 'Diana Prince')

2.Nested Tuples

hero1 = ("Batman", "Bruce Wayne")
hero2 = ("Wonder Woman", "Diana Prince")
awesome_team = (hero1, hero2)
print(awesome_team)

0.470s
(('Batman', 'Bruce Wayne'), ('Wonder Woman', 'Diana Prince'))

3.Search

cities = ("London", "Paris", "Los Angeles", "Tokyo")
print("Moscow" in cities)
#False
cities = ("London", "Paris", "Los Angeles", "Tokyo")
print(cities.index("Tokyo"))
#3

index() 定位
4.Immutability
Since tuples are immutable, we can’t add or delete elements from them. Furthermore, it isn’t possible to append another tuple to an existing tuple.

Dictionaries {}

Dictionaries are unordered because the entries are not stored in a linear structure.
1.Creating a Dictionary

empty_dict = {}  # Empty dictionary
print(empty_dict)

phone_book = {"Batman": 468426,
              "Cersei": 237734,
              "Ghostbusters": 44678}
print(phone_book)
#{}
#{'Cersei': 237734, 'Ghostbusters': 44678, 'Batman': 468426}

2.Accessing Values

#Accessing Values
phone_book = {"Batman": 468426,
              "Cersei": 237734,
              "Ghostbusters": 44678}
print(phone_book["Cersei"])
print(phone_book.get("Ghostbusters"))

#237734
#44678

3.Dictionary Operations

phone_book = {"Batman": 468426,
              "Cersei": 237734,
              "Ghostbusters": 44678}
print(phone_book) 
#{'Cersei': 237734, 'Ghostbusters': 44678, 'Batman': 468426}
phone_book["Godzilla"] = 46394  # New entry
print(phone_book)
#{'Godzilla': 46394, 'Cersei': 237734, 'Ghostbusters': 44678, 'Batman': 468426}
phone_book["Godzilla"] = 9000  # Updating entry
print(phone_book)
#{'Godzilla': 9000, 'Cersei': 237734, 'Ghostbusters': 44678, 'Batman': 468426}
del phone_book["Batman"]
print(phone_book)
#{'Cersei': 237734, 'Ghostbusters': 44678}

If we want to use the deleted value, the pop() or popitem() methods would work better:

cersei = phone_book.pop("Cersei")
print(phone_book)
print(cersei)
#{'Batman': 468426, 'Ghostbusters': 44678}
#237734

# Removes and returns an arbitrary pair as a tuple
lastAdded = phone_book.popitem()
print(lastAdded)
#('Batman', 468426)
phone_book = {"Batman": 468426,
              "Cersei": 237734,
              "Ghostbusters": 44678}
print(len(phone_book))
#3

To copy the contents of one dictionary to another, we can use the update() operation:

phone_book = {"Batman": 468426,
              "Cersei": 237734,
              "Ghostbusters": 44678}

second_phone_book = {"Catwoman": 67423, "Jaime": 237734, "Godzilla": 37623}

# Add secondphone_book to phone_book
phone_book.update(second_phone_book)
print(phone_book)
#{'Batman': 468426, 'Ghostbusters': 44678, 'Jaime': 237734, 'Catwoman': 67423, 'Godzilla': 37623, 'Cersei': 237734}

To iterate the dictionary, we’ll use the dict.items() operation which turns a dictionary into a list of (key, value) tuples.
Here’s a simple example where the keys of the original dictionary are squared and ‘!’ is appended to each string value:

houses = {1: "Gryffindor", 2: "Slytherin", 3: "Hufflepuff", 4: "Ravenclaw"}
new_houses = {n**2: house + "!" for (n, house) in houses.items()}
print(houses)
print(new_houses)
#{1: 'Gryffindor', 2: 'Slytherin', 3: 'Hufflepuff', 4: 'Ravenclaw'}
#{16: 'Ravenclaw!', 1: 'Gryffindor!', 4: 'Slytherin!', 9: 'Hufflepuff!'}

Sets
A set is an unordered collection of data items.
The data is not indexed, so we can’t access elements using indices or get().
在这里插入图片描述
Mutable data structures like lists or dictionaries can’t be added to a set. However, adding a tuple is perfectly fine.

One might wonder, “Why would I need a set?”

Well, a set is perfect when we simply need to keep track of the existence of items.

It doesn’t allow duplicates, which means that we can convert another data structure to a set to remove any duplicates.

random_set = {"Educative", 1408, 3.142,
              (True, False)}
print(random_set)
print(len(random_set))  # Length of the set
#{1408, (True, False), 3.142, 'Educative'}
#4
empty_set = set()
print(empty_set)

random_set = set({"Educative", 1408, 3.142, (True, False)})
print(random_set)
#set()
#{1408, 'Educative', (True, False), 3.142}
empty_set = set()
print(empty_set)

empty_set.add(1)
print(empty_set)

empty_set.update([2, 3, 4, 5, 6])
print(empty_set)
#set()
#{1}
#{1, 2, 3, 4, 5, 6}
random_set = set({"Educative", 1408, 3.142, (True, False)})
print(random_set)

random_set.discard(1408)
print(random_set)

random_set.remove((True, False))
print(random_set)
#{1408, 'Educative', (True, False), 3.142}
#{'Educative', (True, False), 3.142}
#{'Educative', 3.142}

The remove() method generates an error if the item is not found, unlike the discard() method.

odd_list = [1, 3, 5, 7]
unordered_set = {9, 10, 11, 12, 13, 14, 15, 16, 17}

for num in unordered_set:
    if(not num % 2 == 0):
        odd_list.append(num)

print(odd_list)
#[1, 3, 5, 7, 9, 11, 13, 15, 17]

Set Theory Operations

The set data structure in Python supports all three conditions :union, intersection, and difference.(和 并 差)

set_A = {1, 2, 3, 4}
set_B = {'a', 'b', 'c', 'd'}

print(set_A | set_B)
print(set_A.union(set_B))
print(set_B.union(set_A))
#{1, 2, 3, 4, 'b', 'c', 'd', 'a'}
#{1, 2, 3, 4, 'b', 'c', 'd', 'a'}
#{'b', 1, 2, 3, 4, 'c', 'd', 'a'}  ##sets are unordered
set_A = {1, 2, 3, 4}
set_B = {2, 8, 4, 16}

print(set_A & set_B)
print(set_A.intersection(set_B))
print(set_B.intersection(set_A))
#{2, 4}
#{2, 4}
#{2, 4}
set_A = {1, 2, 3, 4}
set_B = {2, 8, 4, 16}

print(set_A - set_B)
print(set_A.difference(set_B))

print(set_B - set_A)
print(set_B.difference(set_A))
#{1, 3}
#{1, 3}
#{16, 8}
#{16, 8}

Data Structure Conversions
Explicit Conversion
The template for explicitly converting from one data structure to another is as follows:

destination_structure_name(source_structure_object)

1.Converting to a List

star_wars_tup = ("Anakin", "Darth Vader", 1000)
print(star_wars_tup)
star_wars_set = {"Anakin", "Darth Vader", 1000}
print(star_wars_set)
star_wars_dict = {1: "Anakin", 2: "Darth Vader", 3: 1000}
print(star_wars_dict)

star_wars_list = list(star_wars_tup)  # Converting from tuple
print(star_wars_list)

star_wars_list = list(star_wars_set)  # Converting from set
print(star_wars_list)

star_wars_list = list(star_wars_dict)  # Converting from dictionary
print(star_wars_list)
#('Anakin', 'Darth Vader', 1000)
#{1000, 'Darth Vader', 'Anakin'}
#{1: 'Anakin', 2: 'Darth Vader', 3: 1000}
#['Anakin', 'Darth Vader', 1000]
#[1000, 'Darth Vader', 'Anakin']
#[1, 2, 3]

We can also use the dict.items() method of a dictionary to convert it into an iterable of (key, value) tuples. This can further be cast into a list of tuples using list():

star_wars_dict = {1: "Anakin", 2: "Darth Vader", 3: 1000}
print(star_wars_dict)

star_wars_list = list(star_wars_dict.items())
print(star_wars_list)
#{1: 'Anakin', 2: 'Darth Vader', 3: 1000}
#[(1, 'Anakin'), (2, 'Darth Vader'), (3, 1000)]

2.Converting to a Tuple

star_wars_list = ["Anakin", "Darth Vader", 1000]
print(star_wars_list)
star_wars_set = {"Anakin", "Darth Vader", 1000}
print(star_wars_set)
star_wars_dict = {1: "Anakin", 2: "Darth Vader", 3: 1000}
print(star_wars_dict)

star_wars_tup = tuple(star_wars_list)  # Converting from list
print(star_wars_tup)

star_wars_tup = tuple(star_wars_set)  # Converting from set
print(star_wars_tup)

star_wars_tup = tuple(star_wars_dict)  # Converting from dictionary
print(star_wars_tup)

#['Anakin', 'Darth Vader', 1000]
#{1000, 'Darth Vader', 'Anakin'}
#{1: 'Anakin', 2: 'Darth Vader', 3: 1000}
#('Anakin', 'Darth Vader', 1000)
#(1000, 'Darth Vader', 'Anakin')
#(1, 2, 3)

3.Converting to a Set

star_wars_list = ["Anakin", "Darth Vader", 1000]
print(star_wars_list)
star_wars_tup = ("Anakin", "Darth Vader", 1000)
print(star_wars_tup)
star_wars_dict = {1: "Anakin", 2: "Darth Vader", 3: 1000}
print(star_wars_dict)

star_wars_set = set(star_wars_list)  # Converting from list
print(star_wars_set)

star_wars_set = set(star_wars_tup)  # Converting from tuple
print(star_wars_set)

star_wars_set = set(star_wars_dict)  # Converting from dictionary
print(star_wars_set)
#['Anakin', 'Darth Vader', 1000]
#('Anakin', 'Darth Vader', 1000)
#{1: 'Anakin', 2: 'Darth Vader', 3: 1000}
#{1000, 'Darth Vader', 'Anakin'}
#{1000, 'Darth Vader', 'Anakin'}
#{1, 2, 3}

4.Converting to a Dictionary #

star_wars_list = [[1,"Anakin"], [2,"Darth Vader"], [3, 1000]]
print (star_wars_list)
star_wars_tup = ((1, "Anakin"), (2, "Darth Vader"), (3, 1000))
print (star_wars_tup)
star_wars_set = {(1, "Anakin"), (2, "Darth Vader"), (3, 1000)}
print (star_wars_set)

star_wars_dict = dict(star_wars_list) # Converting from list
print(star_wars_dict)

star_wars_dict = dict(star_wars_tup) # Converting from tuple
print(star_wars_dict)

star_wars_dict = dict(star_wars_set) # Converting from set
print(star_wars_dict)
#[[1, 'Anakin'], [2, 'Darth Vader'], [3, 1000]]
#((1, 'Anakin'), (2, 'Darth Vader'), (3, 1000))
#{(3, 1000), (1, 'Anakin'), (2, 'Darth Vader')}
#{1: 'Anakin', 2: 'Darth Vader', 3: 1000}
#{1: 'Anakin', 2: 'Darth Vader', 3: 1000}
#{1: 'Anakin', 2: 'Darth Vader', 3: 1000}

EXERCISE:
Problem Statement #
You must implement the count_low_high() function. Its parameter is a list of numbers.

If a number is greater than 50 or divisible by 3, it will count as a high. If these conditions are not met, the number is considered a low.

At the end of the function, you must return a list that contains the number of lows and highs, in that order.

In case the list is empty, you may return None.

Sample Input #
num_list = [20, 9, 51, 81, 50, 42, 77]
Sample Output #
[2, 5] # 2 lows and 5 highs

def count_low_high(num_list):
    high_list = list(filter(lambda n: n > 50 or n % 3 == 0, num_list))
    low_list = list(filter(lambda n: n <= 50 and not n % 3 == 0, num_list))
    return [len(low_list), len(high_list)]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值