Python?推導(dǎo)式、生成器與切片問題解決思路
推導(dǎo)式、生成器與切片
一、實(shí)驗(yàn)要求
1.理解并掌握序列中的常用操作。
2.理解并掌握推導(dǎo)式、切片等用法并能解決實(shí)際問題。
二、實(shí)驗(yàn)內(nèi)容
1,編寫程序,測試字符的出現(xiàn)頻率。
#use dict method1
data = ['a','2',2,3,6,'2','b',4,7,2,'6','d',6,'a','z']
frequences=dict()
for item in data:
if item in frequences:
frequences[item] += 1
else:
frequences[item] = 1
print frequences
#use dict method2
frequences = dict()
for item in data:
frequences[item] = frequences.get(item,0) + 1
print frequences#use defaultdict
from collections import defaultdict
frequences = defaultdict(int)
for item in data:
frequences[item] += 1
print frequences.items()#use set and list type
count_set = set(data)
count_list = []
for item in count_set:
count_list.append((item,data.count(item)))
print count_list#use collections.Counter from collections import Counter frequences = Counter(data) print frequences.items() print list(frequences.elements()) #list all the elements print frequences.most_common(3)
2, 編寫程序求100以內(nèi)的所有奇數(shù)的和。
sum = 0 for i in range(1,100,2): sum = sum + i print(sum)
3,編寫程序,生成包含30個(gè)隨機(jī)整數(shù)的列表,然后對偶數(shù)下標(biāo)的元素降序排列,奇數(shù)下標(biāo)的元素不變。
import random x = [random.randint(0,100) for i in range(30)] #print(x) 打印x看看原列表 y = x[::2] #print(y) 打印偶數(shù)坐標(biāo) y.sort(reverse=True) x[::2] = y print(x)
到此這篇關(guān)于Python 推導(dǎo)式、生成器與切片的文章就介紹到這了,更多相關(guān)Python 推導(dǎo)式、生成器與切片內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python后臺開發(fā)Django的教程詳解(啟動(dòng))
這篇文章主要介紹了Python后臺開發(fā)Django(啟動(dòng)),本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下2019-04-04
Python實(shí)現(xiàn)公歷(陽歷)轉(zhuǎn)農(nóng)歷(陰歷)的方法示例
這篇文章主要介紹了Python實(shí)現(xiàn)公歷(陽歷)轉(zhuǎn)農(nóng)歷(陰歷)的方法,涉及農(nóng)歷算法原理及Python日期運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2017-08-08
Python爬蟲使用Selenium+PhantomJS抓取Ajax和動(dòng)態(tài)HTML內(nèi)容
這篇文章主要介紹了Python爬蟲使用Selenium+PhantomJS抓取Ajax和動(dòng)態(tài)HTML內(nèi)容,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02
Python argparse 解析命令行參數(shù)模塊詳情
這篇文章主要介紹了Python argparse 解析命令行參數(shù)模塊詳情,argparse是python用于解析命令行參數(shù)和選項(xiàng)的標(biāo)準(zhǔn)模塊,用于代替已經(jīng)過時(shí)的optparse模塊2022-07-07
django數(shù)據(jù)模型on_delete, db_constraint的使用詳解
這篇文章主要介紹了django數(shù)據(jù)模型on_delete, db_constraint的使用詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
Python操作SQLite數(shù)據(jù)庫過程解析
這篇文章主要介紹了Python操作SQLite數(shù)據(jù)庫過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09

