61. How will you reverse a list?
list.reverse() − Reverses objects of list in place.
61. How will you sort a list?
list.sort([func]) − Sorts objects of list, use compare func if given.
62. Multiple assignment
>>> target_color_name = first_color_name = 'FireBrick'
>>> id(target_color_name) == id(first_color_name)
True
>>> print(target_color_name)
FireBrick
>>> print(first_color_name)
FireBrick
>>>
63. Word count
import sys
def count_words(filename):
results = dict()
with open(filename, 'r') as f:
for line in f:
for word in line.split():
results[word] = results.setdefault(word, 0) + 1
for word, count in sorted(results.items(), key=lambda x: x[1]):
print('{} {}'.format(count, word))
count_words(sys.argv[1])
64. Word list
from urllib.request import urlopen
with urlopen('http://sixty-north.com/c/t.txt') as story:
story_words = []
for line in story:
line_words = line.split()
for word in line_words:
story_words.append(word)
print(story_words)
65. """Demonstrate scoping."""
count = 0
def show_count():
print("count = ", count)
def set_count(c):
global count
count = c
list.reverse() − Reverses objects of list in place.
61. How will you sort a list?
list.sort([func]) − Sorts objects of list, use compare func if given.
62. Multiple assignment
>>> target_color_name = first_color_name = 'FireBrick'
>>> id(target_color_name) == id(first_color_name)
True
>>> print(target_color_name)
FireBrick
>>> print(first_color_name)
FireBrick
>>>
63. Word count
import sys
def count_words(filename):
results = dict()
with open(filename, 'r') as f:
for line in f:
for word in line.split():
results[word] = results.setdefault(word, 0) + 1
for word, count in sorted(results.items(), key=lambda x: x[1]):
print('{} {}'.format(count, word))
count_words(sys.argv[1])
64. Word list
from urllib.request import urlopen
with urlopen('http://sixty-north.com/c/t.txt') as story:
story_words = []
for line in story:
line_words = line.split()
for word in line_words:
story_words.append(word)
print(story_words)
65. """Demonstrate scoping."""
count = 0
def show_count():
print("count = ", count)
def set_count(c):
global count
count = c
No comments:
Post a Comment