def functionname( parameters ):
"函数_文档字符串"
function_suite
return [expression]
def score_info(name, **kw):
if '语文成绩' in kw:
print(name, '的语文成绩', kw['语文成绩'])
if '数学成绩' in kw:
print(name, '的数学成绩', kw['数学成绩'])
def person_info(name, age, **kw):
print('姓名:', name, ' 年龄',age)
score_info(name, **kw)
score_cfg = {
'语文成绩':65, '数学成绩':60}
person_info('张三', 18, **score_cfg)
map() 函数会根据提供的函数对指定序列做映射。第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
map(function, iterable, …)。
Python 2.x 返回列表。Python 3.x 返回迭代器。
reduce() 函数会对参数序列中元素进行累积。函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。
reduce(function, iterable[, initializer])
sorted() 函数对所有可迭代的对象进行排序操作。sorted(iterable, cmp=None, key=None, reverse=False)
偏函数:将所要承载的函数作为partial()函数的第一个参数,原函数的各个参数依次作为partial()函数后续的参数,除非使用关键字参数。from functools import partial
装饰器(Decorators):修改其他函数的功能的函数。装饰器最大的优势是用于解决重复性的操作,其主要使用的场景有如下几个:
# 装饰器输入一个函数,输出一个函数
def print_working(func):
def wrapper():
print(f'{func.__name__} is working...')
func()
return wrapper
def worker1():
print('我是一个勤劳的工作者!')
def worker2():
print('我是一个勤劳的工作者!')
def worker3():
print('我是一个勤劳的工作者!')
worker1 = print_working(worker1)
worker1()
worker2= print_working(worker2)
worker2()
worker3= print_working(worker2)
worker3()
@print_working
def worker1():
print('我是一个勤劳的工作者!')
@print_working
def worker2():
print('我是一个勤劳的工作者!')
@print_working
def worker3():
print('我是一个勤劳的工作者!')
worker1()
worker2()
worker3()
闭包(Closure):一个函数定义中引用了函数外定义的变量,并且该函数可以在其定义环境外被执行。这样的一个函数我们称之为闭包。
# 一个需要注意的问题是,返回的函数并没有立刻执行,而是直到调用了f()才执行。
def count():
fs = []
for i in range(1, 4):
def f():
# print(id(i))
return i*i
fs.append(f)
return fs
f1, f2, f3 = count()
print(f1())
print(f2())
print(f3())
输出:
9
9
9
def count():
def f(j):
def g():
# print(id(j))
return j*j
return g
fs = []
for i in range(1, 4):
fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f()
return fs
f1, f2, f3 = count()
print(f1())
print(f2())
print(f3())
输出:
1
4
9
作业内容:
统计英语6级试题中所有单词的词频,并返回一个如下样式的字典
{‘and’:100,‘abandon’:5}
英语6级试题的文件路径./artical.txt
Tip: 读取文件的方法
def get_artical(artical_path):
with open(artical_path) as fr:
data = fr.read()
return data
get_artical('./artical.txt')
处理要求:
# 请根据处理要求下面区域完成代码的编写。
def get_artical(artical_path):
with open(artical_path) as fr:
data = fr.read()
return data
# get_artical()为自定义函数,可用于读取指定位置的试题内容。
str_artical=get_artical('./artical.txt')
import string
# 去除数字
from string import digits
str_digits = str_artical.translate(str.maketrans('', '', digits))
# 去除符号
from string import punctuation
str_punctuation = str_digits.translate(str.maketrans('', '', punctuation))
# 去除选项中ABCD字母(题目没要求,个人添加)
#str_question = str_punctuation.translate(str.maketrans('', '', 'ABCD'))
# 小写
str_lower=str_question.lower()
# 去除空字符,切片
str_spilt=str_lower.split()
# 打印词频列表
num_words = {
}
for str_spilt in str_spilt:
num_words[str_spilt] = num_words.get(str_spilt, 0) + 1
print(num_words)
# 输出词频txt文本文件(题目没要求)
s = str(num_words)
f = open('dict.txt','w')
f.writelines(s)
f.close()
# 词频查询(题目没要求)
str_spilt=str_lower.split()
word=input('输入要查询的单词的次数')
print(str_spilt.count(word))
——以下为作业所需article.txt文档内容——
Passage One
Questions 46 to 50 are based on the following passage.
Last year, a child was born at a hospital in the UK with her heart outside her body. Few babies survive this rare condition, and those who do must endure numerous operations and are likely to have complex needs. When her mother was interviewed, three weeks after her daughter’s birth, she was asked if she was prepared for what might be a daunting task caring for her. She answered without hesitation that, as far as she was concerned, this would be a “privilege”.
Rarely has there been a better example of the power of attitude, one of our most powerful psychological tools. Our attitudes allow us to turn mistakes into opportunities, and loss into the chance for new beginnings. An attitude is a settled way of thinking, feeling and/or behaving towards particular objects, people, events or ideologies. We use our attitudes to filter, interpret and react to the world around us. You weren’t born with attitudes, rather they are all learned, and this happens in a number of ways.
The most powerful influences occur during early childhood and include both what happened to you directly, and what those around you did and said in your presence. As you acquire a distinctive identity, your attitudes are further refined by the behavior of those with whom you identify – your family, those of your gender and culture, and the people you admire, even though you may not know them personally. Friendships and other important relationships become increasingly important, particularly during adolescence. About that same time and throughout adulthood, the information you receive, especially when ideas are repeated in association with goals and achievements you find attractive, also refines your attitudes.
Many people assume that our attitudes are internally consistent, that is, the way you think and feel about someone or something predicts your behavior towards them. However, may studies have found that feelings and thoughts don’t necessarily predict behavior. In general, your attitudes will be internally consistent only when the behavior is easy, and when those around you hold similar beliefs. That’s why, for example, may say they believe in the benefits of recycling or exercise, but don’t behave in line with their views, because it takes awareness, effort and courage to go beyond merely stating that you believe something is a good idea.
One of the most effective ways to change an attitude is to start behaving as if you already feel and think the way you’d prefer to. Take some time to reflect on your attitudes, to think about what you believe and why. Is there anything you consider a burden rather than a privilege? It so, start behaving – right now – as if the latter is the case.
Passage Two
Questions 51 to 55 are based on the following passage.
Industrial fishing for krill in the unspoilt waters around Antarctica is threatening the future of one of the world’s last great wildernesses, according to a new report.
The study by Greenpeace analysed the movements of krill fishing vessels in the region and found they were increasingly operating “in the immediate vicinity of penguin colonies and whale feeding grounds”. It also highlights incidents of fishing boats being involved in groundings, oil spills and accidents, which posed a serious threat to the Antarctic ecosystem.
The report, published on Tuesday, comes amid growing concern about the impact of fishing. and climate change on the Antarctic. A global campaign has been launched to create a network of ocean sanctuaries to protect the seas in the region and Greenpeace is calling for an immediate halt to fishing in areas being considered for sanctuary status.
Frida Bengtsson from Greenpeace’s Protect the Antarctic campaign said: “If the krill industry wants to show it’s a responsible player, then it should be voluntarily getting out of any area which is being proposed as an ocean sanctuary, and should instead be backing the protection of these huge tracts of the Antarctic.”
A global campaign has been launched to turn a huge tract of Antarctic seas into ocean sanctuaries, protecting wildlife and banning not just krill fishing, but all fishing. One was created in the Ross Sea in 2016, another reserve is being proposed in a vast area of the Weddell Sea, and a third sanctuary is under consideration in the area west of the Antarctic Peninsula – a key krill fishing area.
The Commission for the Conservation of Antarctic Marine Living Resources (CCAMLR) manages the seas around Antarctica. It will decide on the Weddell Sea sanctuary proposal at a conference in Australia in October, although a decision on the peninsula sanctuary is not expected until later.
Keith Reid, a science manager at CCAMLR, said that the organisation sought “a balance between protection, conservation and sustainable fishing in the Southern Ocean.” He said although more fishing was taking place nearer penguin colonies it was often happening later in the season when these colonies were empty.
“The creation of a system of marine protected areas is a key part of ongoing scientific and policy discussions in CCAMLR,” he added. “Our long-term operation in the region depends on a healthy and thriving Antarctic marine ecosystem, which is why we have always had an open dialogue with the environmental non-governmental organisations. We strongly intend to continue this dialogue, including talks with Greenpeace, to discuss improvements based on the latest scientific data. We are not the ones to decide on the establishment of marine protected areas, but we hope to contribute positively with our knowledge and experience.”
Passage One
Questions 46 to 50 are based on the following passage.
Schools are not just a microcosm of society; they mediate it too. The best seek to alleviate the external pressures on their pupils while equipping them better to understand and handle the world outside – at once sheltering them and broadening their horizons. This is ambitious in any circumstances, and in a divided and unequal society the two ideals can clash outright.
Trips that many adults would consider the adventure of a lifetime – treks in Bomeo, a sports tour to Barbados – appear to have become almost routine at some state schools. Parents are being asked for thousands of pounds. Though schools cannot profit from these trips, the companies that arrange them do. Meanwhile, pupils arrive at school hungry because their families can’t afford breakfast. The Child Poverty Action Group says nine out of 30 in every classroom fall below the poverty line. The discrepancy is startlingly apparent. Introducing a fundraising requirement for students does not help, as better-off children can tap up richer aunts and neighbours.
Probing the rock pools of a local beach or practising French on a language exchange can fire children’s passions, boost their skills and open their eyes to life 's possibilities. Educational outings help bright but disadvantaged students to get better scores in A-level tests. In this globalised age, there is a good case for international travel, and some parents say they can manage the cost of a school trip abroad more easily than a family holiday. Even in the face of immense and mounting financial pressures, some schools have shown remarkable determination and ingenuity in ensuring that all their pupils are able to take up opportunities that may be truly life-changing. They should be applauded. Methods such as whole-school fundraising, with the proceeds pooled, can help to extend opportunities and fuel community spirit.
But 3,000 pounds trips cannot be justified when the average income for families with children is just over 30,000 pounds. Such initiatives close doors for many pupils. Some parents pull their children out of school because of expensive field trips. Even parents who can see that a trip is little more than a party or celebration may well feel guilt that their child is left behind.
The Department for Education 's guidance says schools can charge only for board and lodging if the trip is part of the syllabus, and that students receiving government aid are exempt from these costs. However, many schools seem to ignore the advice; and it does not cover the kind of glamorous, exotic trips, which are becoming increasingly common. Schools cannot be expected to bring together communities single-handed. But the least we should expect is that they do not foster divisions and exclude those who are already disadvantaged.
Passage Two
Questions 51 to 55 are based on the following passage.
Rising temperatures and overfishing in the pristine waters around the Antarctic could see king penguin populations pushed to the brink of extinction by the end of the century, according to a new study. The study’s report states that as global warming transforms the environment in the world’s last great wilderness, 70 percent of king penguins could either disappear or be forced to find new breeding grounds.
Co-author Celine Le Bohec, from the University of Strasbourg in France, warned: “If there’re no actions aimed at halting or controlling global warming, and the pace of the current human-induced changes such as climate change and overfishing stays the same, the species may soon disappear.” The findings come amid growing concern over the future of the Antarctic. Earlier this month a separate study found that a combination of climate change and industrial fishing is threatening the krill population in Antarctic waters, with a potentially disastrous impact on whales, seals and penguins. But today’s report is the starkest warming yet of the potentially devastating impact of climate change and human exploitation on the Antarctic’s delicate ecosystems.
Le Bohec said: “Unless current greenhouse gas emissions drop, 70 percent of king penguins – 1.1 million breeding pairs – will be forced to relocate their breeding grounds, or face extinction by 2100.” King penguins are the second-largest type of penguin and only breed on specific isolated islands in the Southern Ocean where there is no ice cover and easy access to the sea. As the ocean warms, a body of water called the Antarctic Polar Front – an upward movement of nutrient-rich sea that supports a huge abundance of marine life – is being pushed further south. This means that king penguins, which feed on fish and kill in this body of water, have to travel further to their feeding grounds, leaving their hungry chicks for longer. And as the distance between their breeding, grounds and their fool prows, entire colonies could be wiped out.
Le Bohec said: “The plight of the king penguin should serve as a warming about the future of the entire marine environment in the Antarctic. Penguins, like other seabirds and marine mammals, occupy higher levels in the food chain and they are what we call bio-indicators of their ecosystems.” Penguins are sensitive indicators of changes in marine ecosystems. As such, they are key species for understanding and predicting impacts of global change on Antarctic and sub-Antarctic marine ecosystems. The report found that although some king penguins may be able to relocate to new breeding grounds closer to their retreating food source, suitable new habitats would be scarce. Only a handful of islands in the Southern Ocean are suitable for sustaining large breeding colonies.