python创建新列表_Python家庭作业-创建新列表

The assignment:

Write a function called splitList(myList, option) that takes, as input, a list and an option, which is either 0 or 1. If the value of the option is 0, the function returns a list consisting of the elements in myList that are negative, and if the value of the option is 1, the function returns a list consisting of the elements in myList that are even.

I know how to determine if a number is even and if a number is negative. I'm struggling with how to return a new list of negative or even numbers based on "option"

This is what I've gotten so far:

def splitList(myList):

newlist = []

for i in range(len(myList)):

if (myList[i]%2 == 0):

newlist.append(myList [i])

return newlist

This program gives the following error:

Traceback (most recent call last): File "", line 1, in

builtins.TypeError: splitList() takes exactly 1 positional argument (4 given)

解决方案

As I mentioned in my comment, you should standardize your indentation: four spaces is Python standard. You can usually set your editor to insert four spaces instead of tabs (don't want to mix tabs with spaces, either).

As to your actual question: try writing three total functions: one that returns all the negative values, one that returns even values, and one that calls the appropriate function based on option.

def splitlist(myList, option):

if option == 1:

return get_even_elements(myList)

elif option == 0:

return get_negative_elements(myList)

def get_even_elements(myList):

pass # Implementation this method here.

def get_negative_elements(myList):

pass # Implementation this method here.

# Test it out!

alist = [-1, 2, -8, 5]

print splitlist(alist, 0)

print splitlist(alist, 1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一份可能的大作业实践方案,可以供您参考: ## 1. 爬虫部分 ### 1.1 需求分析 根据题目要求,需要编写一个爬虫程序,爬取指定网站的数据。在爬取数据的过程中,需要做到: - 发送请求,获取网页内容 - 解析网页内容,提取所需数据 - 存储数据,方便后续的数据分析和可视化操作 ### 1.2 技术选型 根据需求分析,可以发现,需要使用 Python 编写爬虫程序。Python 有很多第三方库可以用来编写爬虫,比如 BeautifulSoup、Scrapy、urllib、requests 等等。这里我们选择使用 urllib 和 re 两个标准库来编写爬虫程序。 ### 1.3 实现步骤 首先,需要确定爬取的目标网站和要爬取的数据。这里我们选择爬取豆瓣电影 Top250 的电影名称、评分和简介等信息。 其次,需要发送请求,获取网页内容。可以使用 urllib 发送请求,并设置请求头模拟浏览器访问。 ```python import urllib.request # 设置请求头,模拟浏览器访问 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3' } # 豆瓣电影 Top250 的 url url = 'https://movie.douban.com/top250' # 发送请求,获取网页内容 try: request = urllib.request.Request(url, headers=headers) response = urllib.request.urlopen(request) content = response.read().decode('utf-8') except Exception as e: print(e) ``` 接着,需要解析网页内容,提取所需数据。可以使用 re 正则表达式来解析网页内容,提取电影名称、评分和简介等信息。 ```python import re # 解析网页内容,获取电影信息 pattern = re.compile(r'<span class="title">(.*?)</span>.*?<span class="rating_num" property="v:average">(.*?)</span>.*?<span class="inq">(.*?)</span>', re.S) movies = re.findall(pattern, content) ``` 然后,需要存储数据,方便后续的数据分析和可视化操作。可以将数据存储到文本文件中,或者使用数据库存储数据。 ```python # 将电影信息保存到文件 with open('movies.txt', 'w', encoding='utf-8') as f: for movie in movies: f.write('电影名称:' + movie[0] + '\n') f.write('评分:' + movie[1] + '\n') f.write('简介:' + movie[2] + '\n\n') ``` ## 2. 数据分析部分 ### 2.1 需求分析 在完成爬虫程序之后,需要对爬取到的数据进行分析。在数据分析的过程中,需要做到: - 统计电影的评分分布情况 - 统计电影的类型分布情况 - 统计电影的上映年份分布情况 ### 2.2 技术选型 根据需求分析,需要使用 Python 对数据进行统计和分析。Python 中有很多第三方库可以用来进行数据分析,比如 pandas、numpy、matplotlib 等等。这里我们选择使用 pandas 和 matplotlib 两个库来进行数据分析和可视化。 ### 2.3 实现步骤 首先,需要读取爬取到的数据。可以使用 pandas 库读取文本文件中的数据。 ```python import pandas as pd # 读取数据 data = pd.read_csv('movies.txt', delimiter=':', header=None, names=['类别', '内容']) ``` 接着,需要将电影评分转换为数字类型,并统计电影的评分分布情况。可以使用 pandas 库的 describe() 方法和 matplotlib 库的 hist() 方法来实现。 ```python import matplotlib.pyplot as plt # 将电影评分转换为数字类型 data['内容'] = pd.to_numeric(data['内容']) # 统计电影的评分分布情况 print(data['内容'].describe()) # 可视化电影的评分分布情况 plt.hist(data['内容'], bins=10, color='steelblue', edgecolor='black') plt.xlabel('评分') plt.ylabel('电影数量') plt.title('电影评分分布情况') plt.show() ``` 然后,需要统计电影的类型分布情况。可以使用 pandas 库的 str.contains() 方法和 value_counts() 方法来实现。 ```python # 统计电影的类型分布情况 types = ['剧情', '喜剧', '动作', '爱情', '科幻', '动画', '悬疑', '惊悚', '恐怖', '纪录片', '短片', '情色', '同性', '音乐', '歌舞', '家庭', '儿童', '传记', '历史', '战争', '犯罪', '西部', '奇幻', '冒险', '灾难', '武侠', '古装', '运动', '黑色电影'] for t in types: print(t + '电影数量:' + str(data[data['类别'].str.contains(t)]['类别'].count())) # 可视化电影的类型分布情况 data[data['类别'].str.contains('|'.join(types))]['类别'].value_counts().plot(kind='bar') plt.xlabel('电影类型') plt.ylabel('电影数量') plt.title('电影类型分布情况') plt.show() ``` 最后,需要统计电影的上映年份分布情况。可以使用 pandas 库的 str.extract() 方法和 value_counts() 方法来实现。 ```python # 统计电影的上映年份分布情况 data['上映年份'] = data['类别'].str.extract('(\d{4})') print(data['上映年份'].value_counts()) # 可视化电影的上映年份分布情况 data['上映年份'].value_counts().sort_index().plot(kind='bar') plt.xlabel('上映年份') plt.ylabel('电影数量') plt.title('电影上映年份分布情况') plt.show() ``` 到此为止,整个数据分析和可视化流程就完成了。将以上代码整合到一个 Python 文件中,并执行该文件,就可以得到统计结果和可视化图表。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值