Podcast
Questions and Answers
以下哪个循环结构用于迭代列表或元组中的每个元素?
以下哪个循环结构用于迭代列表或元组中的每个元素?
- `for...in` 循环 (correct)
- `if...else` 循环
- `do...while` 循环
- `while` 循环
在 while
循环中,只要条件满足,循环就会无限期地继续执行。
在 while
循环中,只要条件满足,循环就会无限期地继续执行。
False (B)
在 Python 中,哪个语句可以提前结束循环的当前迭代并继续执行下一次迭代?
在 Python 中,哪个语句可以提前结束循环的当前迭代并继续执行下一次迭代?
continue
在循环中,________ 语句可以完全退出循环。
在循环中,________ 语句可以完全退出循环。
将以下循环相关任务与相应的 Python 语句匹配:
将以下循环相关任务与相应的 Python 语句匹配:
以下哪个选项不是 dict
的有效特征?
以下哪个选项不是 dict
的有效特征?
如果 key
不存在,则尝试访问 dict
中不存在的 key
将返回 None
。
如果 key
不存在,则尝试访问 dict
中不存在的 key
将返回 None
。
在 Python 中,从 dict
中删除 key-value
对的适当方法是什么?
在 Python 中,从 dict
中删除 key-value
对的适当方法是什么?
与 list
不同,__________ 需要大量内存。
与 list
不同,__________ 需要大量内存。
将以下 dict
方法与它们的描述匹配:
将以下 dict
方法与它们的描述匹配:
set
数据结构用于以下哪个目的?
set
数据结构用于以下哪个目的?
set
允许重复元素。
set
允许重复元素。
用于将元素添加到 set
的方法是什么?
用于将元素添加到 set
的方法是什么?
使用 __________ 方法从 set
中删除元素。
使用 __________ 方法从 set
中删除元素。
将以下 set
操作与其用途相匹配:
将以下 set
操作与其用途相匹配:
为什么可变对象不能用作 dict
或 set
中的 key
?
为什么可变对象不能用作 dict
或 set
中的 key
?
字符串是 Python 中的可变对象。
字符串是 Python 中的可变对象。
在字符串是不可变的上下文中,“不变性”是什么意思?
在字符串是不可变的上下文中,“不变性”是什么意思?
对于不变的对象(如字符串),修改值的方法会返回 __________。
对于不变的对象(如字符串),修改值的方法会返回 __________。
匹配不变性和可变性与它们的数据类型:
匹配不变性和可变性与它们的数据类型:
Flashcards
for...in 循环
for...in 循环
Python 中的一种循环结构,用于迭代列表或元组中的每个元素。
while 循环
while 循环
当条件满足时,不断重复执行循环体内的代码,直到条件不再满足时退出循环。
break
break
一个可以提前退出循环的语句。
continue
continue
Signup and view all the flashcards
dict (字典)
dict (字典)
Signup and view all the flashcards
KeyError
KeyError
Signup and view all the flashcards
set (集合)
set (集合)
Signup and view all the flashcards
可变与不可变对象
可变与不可变对象
Signup and view all the flashcards
add(key)
add(key)
Signup and view all the flashcards
remove(key)
remove(key)
Signup and view all the flashcards
Study Notes
- This section discusses loops in Python and how to use dictionaries (
dict
) and sets (set
).
循环 (Loops)
- Loops are used to perform repetitive calculations.
- Python offers two types of loops:
for...in
andwhile
.
for...in 循环
- This loop iterates through each element in a
list
ortuple
. - Example:
names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)
-
This code prints each name in the
names
list. -
The loop assigns each element to the variable
x
, then executes the indented block. -
To calculate the sum of integers from 1-10 the following code can be used:
sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
sum = sum + x
print(sum)
- The
range()
function generates a sequence of integers.list(range(5))
creates a list[0, 1, 2, 3, 4]
.range(101)
generates a sequence from 0-100.
while 循环
-
The
while
loop continues as long as a condition is met. -
The loop exits when the condition is no longer true.
-
Example for sum of odd numbers less than 100:
sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print(sum)
- Inside the loop,
n
decrements until it becomes -1, at which point thewhile
condition is no longer met, and the loop terminates.
break 语句
-
The
break
statement exits the loop prematurely. -
Example:
n = 1
while n <= 100:
if n > 10:
break
print(n)
n = n + 1
print('END')
- This code prints numbers 1-10 and then prints 'END'.
continue 语句
-
The
continue
statement skips the current iteration and proceeds to the next. -
Example:
n = 0
while n < 10:
n = n + 1
if n % 2 == 0:
continue
print(n)
- This code prints odd numbers less than 10.
循环小结
- Loops automate repetitive tasks.
break
exits a loop, whilecontinue
skips an iteration.- Use
if
statements withbreak
andcontinue
. - Avoid overuse of
break
andcontinue
to keep code clear.
dict (Dictionaries)
- Dictionaries store key-value pairs (
key-value
). - They offer fast lookups.
- Example:
names = ['Michael', 'Bob', 'Tracy']
scores = [95, 75, 85]
-
In this case, to look up the grade of a student, one would need to search the names list and get the index, and then use the index to look up the grade in the scores list.
-
With
dict
, you create a table of "name"-"score" correspondences, and can look this up directly -
Dictionary example:
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
print(d['Michael']) # Output: 95
- The key is a name, and the value is the corresponding score.
- Dictionaries are fast because they use lookups similar to a dictionary index.
- Data can be put into a
dict
using:
d['Adam'] = 67
- If a key is assigned multiple values, the last value overwrites previous values.
d['Jack'] = 90
d['Jack'] = 88
print(d['Jack']) # Output: 88
-
If a key does not exist, an error occurs. To avoid this:
- Check if the key exists using
in
:'Thomas' in d
returnsFalse
. - Use
get()
:d.get('Thomas')
returnsNone
, andd.get('Thomas', -1)
returns-1
.
- Check if the key exists using
-
The
pop(key)
method removes a key-value pair:d.pop('Bob')
removes Bob's entry. -
Key features of
dict
:- Fast lookups and insertions.
- Large memory usage due to wasted space.
-
Key features of
list
are the opposite ofdict
:- Lookups and insertions slow as elements increase.
- Small memory footprint.
-
Use immutable objects as dictionary keys eg strings.
set
- Similar to
dict
, aset
is a collection of keys, without associated values. - Keys in a
set
do not repeat. - To create a
set
, provide alist
as input:
s = set([1, 2, 3])
print(s) # Output: {1, 2, 3}
- Duplicate elements are automatically filtered out.
s = set([1, 1, 2, 2, 3, 3])
print(s) # Output: {1, 2, 3}
-
add(key)
adds elements to the set. Adding an element multiple times has no effect. -
remove(key)
removes elements from the set. -
Sets can be used for mathematical operations like intersection and union.
s1 = set([1, 2, 3])
s2 = set([2, 3, 4])
print(s1 & s2) # Intersection: {2, 3}
print(s1 | s2) # Union: {1, 2, 3, 4}
- Sets can't hold mutable objects because they can't determine whether the two mutable objects are equal and can't ensure the 'no repeat element' condition.
不可变对象 (Immutable Objects)
str
is immutable, whilelist
is mutable.- For a mutable object, such as
list
, the internal content changes when you modify the list.
a = ['c', 'b', 'a']
a.sort()
print(a) # Output: ['a', 'b', 'c']
- For immutable objects like
str
, operations don't change the object.
a = 'abc'
a.replace('a', 'A')
print(a) # Output: abc
- The
replace()
method doesn't change the original string, but creates a new string. - The variable
a
still points to the original string 'abc'.
a = 'abc'
b = a.replace('a', 'A')
print(b) # Output: Abc
print(a) # Output: abc
- When you call an attribute method you create a new object, which is why immutable objects stay immutable, even after method calls such as replace().
总结
- Dictionaries are useful for key-value storage and immutable objects such as strings are chosen as keys, tuples also work in dictionaries and sets, but must use immutable objects.
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.