chapter 4 WORKING WITH LISTS

Looping Through an Entire List

  • When you want to do the same action with every item in a list, you can use Python’s for loop.
magicians = ['alice', 'david', 'carolina'] 
for magician in magicians: 
	print(magician)
  • 注意for循环后的冒号
  • 注意缩进
  • A Closer Look at Looping
    • Also keep in mind when writing your own for loops that you can choose any name you want for the temporary variable that will be associated with each value in the list.
    • However, it’s helpful to choose a meaningful name that represents a single item from the list.
    • Using singular and plural names can help you identify whether a section of code is working with a single element from the list or the entire list.
  • Doing More Work Within a for Loop
    • You can also write as many lines of code as you like in the for loop. Every indented line following the line for magician in magicians is considered inside the loop, and each indented line is executed once for each value in the list.
magicians = ['alice', 'david', 'carolina'] 
for magician in magicians: 
	print(f"{magician.title()}, that was a great trick!") 
	print(f"I can't wait to see your next trick, {magician.title()}.\n")
  • Doing Something After a for Loop
    • Any lines of code after the for loop that are not indented are executed once without repetition.
magicians = ['alice', 'david', 'carolina'] 
for magician in magicians: 
	print(f"{magician.title()}, that was a great trick!") 
	print(f"I can't wait to see your next trick, {magician.title()}.\n")
	print("Thank you, everyone. That was a great magic show!")

Avoiding Indentation Errors

  • Python uses indentation to determine how a line, or group of lines, is related to the rest of the program.
  • Forgetting to Indent
    • Always indent the line after the for statement in a loop.
  • Forgetting to Indent Additional Lines
    • Sometimes your loop will run without any errors but won’t produce the expected result. This can happen when you’re trying to do several tasks in a loop and you forget to indent some of its lines.
  • Indenting Unnecessarily
    • You can avoid unexpected indentation errors by indenting only when you have a specific reason to do so.
    • In the programs you’re writing at this point, the only lines you should indent are the actions you want to repeat for each item in a for loop
  • Indenting Unnecessarily After the Loop
    • If an action is repeated many times when it should be executed only once, you probably need to unindent the code for that action.
  • Forgetting the Colon
    • The colon at the end of a for statement tells Python to interpret the next line as the start of a loop.

Making Numerical Lists

  • Using the range() Function
    • Python’s range() function makes it easy to generate a series of numbers.
    • Although this code looks like it should print the numbers from 1 to 5, it doesn’t print the number 5
    • The range() function causes Python to start counting at the first value you give it, and it stops when it reaches the second value you provide.
    • Because it stops at that second value, the output never contains the end value, which would have been 5 in this case.
for value in range(1, 5): 
	print(value)
    • You can also pass range() only one argument, and it will start the sequence of numbers at 0.
    • For example, range(6) would return the numbers from 0 through 5.
  • Using range() to Make a List of Numbers

    • If you want to make a list of numbers, you can convert the results of range() directly into a list using the list() function.
    • When you wrap list() around a call to the range() function, the output will be a list of numbers
numbers = list(range(1, 6)) 
print(numbers)
    • We can also use the range() function to tell Python to skip numbers in a given range. If you pass a third argument to range(), Python uses that value as a step size when generating numbers.
even_numbers = list(range(2, 11, 2)) 
print(even_numbers)

[2, 4, 6, 8, 10]
  • Simple Statistics with a List of Numbers

    • A few Python functions are helpful when working with lists of numbers.
    • For example, you can easily find the minimum, maximum, and sum of a list of numbers
      在这里插入图片描述
  • List Comprehensions

    • A list comprehension combines the for loop and the creation of new elements into one line, and automatically appends each new element.
squares = [value**2 for value in range(1, 11)] 
print(squares)

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Working with Part of a List

  • You can also work with a specific group of items in a list, called a slice in Python.
  • Slicing a List
    • To make a slice, you specify the index of the first and last elements you want to work with.
    • As with the range() function, Python stops one item before the second index you specify.
    • If you omit the first index in a slice, Python automatically starts your slice at the beginning of the list
    • A similar syntax works if you want a slice that includes the end of a list. For example, if you want all items from the third item through the last item, you can start with index 2 and omit the second index
    • You can include a third value in the brackets indicating a slice. If a third value is included, this tells Python how many items to skip between items in the specified range.【改变的是索引,在上一个索引值上加上步长等于下一个需要输出的索引】
players = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[0:3])
----------------------------------
['charles', 'martina', 'michael']
  • Looping Through a Slice
    • You can use a slice in a for loop if you want to loop through a subset of the elements in a list.
players = ['charles', 'martina', 'michael', 'florence', 'eli'] print("Here are the first three players on my team:")  
for player in players[:3]: 
	print(player.title())
----------------------------------------------------------------
Here are the first three players on my team: 
Charles 
Martina 
Michael
  • Copying a List
    • To copy a list, you can make a slice that includes the entire original list by omitting the first index and the second index ([:]).
    • This tells Python to make a slice that starts at the first item and ends with the last item, producing a copy of the entire list.
    • 注意区别:
      • friend_foods = my_foods[:]
      • friend_foods = my_foods
      • Instead of assigning a copy of my_foods to friend_foods, we set friend_foods equal to my_foods. This syntax actually tells Python to associate the new variable friend_foods with the list that is already associated with my_foods, so now both variables point to the same list.
my_foods = ['pizza', 'falafel', 'carrot cake']  
friend_foods = my_foods[:] 
print("My favorite foods are:") 
print(my_foods) 
print("\nMy friend's favorite foods are:") 
print(friend_foods)
---------------------------------------------------
My favorite foods are: 
['pizza', 'falafel', 'carrot cake'] 

My friend's favorite foods are: 
['pizza', 'falafel', 'carrot cake']

Tuples

  • Lists work well for storing collections of items that can change throughout the life of a program. The ability to modify lists is particularly important when you’re working with a list of users on a website or a list of characters in a game.
  • However, sometimes you’ll want to create a list of items that cannot change. Tuples allow you to do just that. Python refers to values that cannot change as immutable, and an immutable list is called a tuple.
  • Defining a Tuple
    • A tuple looks just like a list, except you use parentheses instead of square brackets.
    • Once you define a tuple, you can access individual elements by using each item’s index, just as you would for a list.
dimensions = (200, 50) 
print(dimensions[0]) 
print(dimensions[1])
————————————————————————————————————————
200 
50
    • Tuples are technically defined by the presence of a comma; the parentheses make them look neater and more readable.
    • If you want to define a tuple with one element, you need to include a trailing comma: my_t = (3,)
    • It doesn’t often make sense to build a tuple with one element, but this can happen when tuples are generated automatically
  • Looping Through All Values in a Tuple
dimensions = (200, 50) 
for dimension in dimensions: 
	print(dimension)
————————————————————————————————————
200 
50
  • Writing Over a Tuple
    • Although you can’t modify a tuple, you can assign a new value to a variable that represents a tuple.
    • When compared with lists, tuples are simple data structures. Use them when you want to store a set of values that should not be changed throughout the life of a program.
dimensions = (200, 50) 
print("Original dimensions:") 
for dimension in dimensions: 
	print(dimension) 
dimensions = (400, 100) 
print("\nModified dimensions:") 
for dimension in dimensions: 
	print(dimension)

————————————————————————————————————————
Original dimensions: 
200 
50 
Modified dimensions: 
400 
100

Styling Your Code

  • Now that you’re writing longer programs, it’s a good idea to learn how to style your code consistently. Take the time to make your code as easy as possible to read. Writing easy-to-read code helps you keep track of what your programs are doing and helps others understand your code as well.
  • The Python style guide was written with the understanding that code is read more often than it is written.
  • Indentation
    • Using four spaces improves readability while leaving room for multiple levels of indentation on each line.
    • In a word processing document, people often use tabs rather than spaces to indent. This works well for word processing documents, but the Python interpreter gets confused when tabs are mixed with spaces. Every text editor provides a setting that lets you use the TAB key but then converts each tab to a set number of spaces. You should definitely use your TAB key, but also make sure your editor is set to insert spaces rather than tabs into your document.
    • If you think you have a mix of tabs and spaces, you can convert all tabs in a file to spaces in most editors.
  • Line Length
    • Don’t worry too much about line length in your code as you’re learning, but be aware that people who are working collaboratively almost always follow the PEP 8 guidelines.
    • Most editors allow you to set up a visual cue, usually a vertical line on your screen, that shows you where these limits are
  • Blank Lines
    • To group parts of your program visually, use blank lines. You should use blank lines to organize your files, but don’t do so excessively.
    • For example, if you have five lines of code that build a list and then another three lines that do something with that list, it’s appropriate to place a blank line between the two sections. However, you should not place three or four blank lines between the two sections.
  • Other Style Guidelines
    • PEP 8 has many additional styling recommendations, but most of the guidelines refer to more complex programs than what you’re writing at this point.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值