[轉載] python基礎入門二

參考鏈接: Python集合Set

寫代碼,有如下變量,請按照要求實現每個功能 (共6分,每小題各0.5分)? name = ” aleX”? 1)移除 name 變量對應的值兩邊的空格,并輸出處理結果? 2) 判斷 name 變量對應的值是否以 “al” 開頭,并輸出結果?? 3) 判斷 name 變量對應的值是否以 “X” 結尾,并輸出結果?? 4) 將 name 變量對應的值中的 “l” 替換為 “p”,并輸出結果? 5) 將 name 變量對應的值根據 “l” 分割,并輸出結果。? 6) 將 name 變量對應的值變大寫,并輸出結果?? 7) 將 name 變量對應的值變小寫,并輸出結果?? 8) 請輸出 name 變量對應的值的第 2 個字符?? 9) 請輸出 name 變量對應的值的前 3 個字符?? 10) 請輸出 name 變量對應的值的后 2 個字符??? 11) 請輸出 name 變量對應的值中 “e” 所在索引位置??? 12) 獲取子序列,去掉最后一個字符。如: oldboy 則獲取 oldbo。?

name = " aleX"

?

?

print(name.strip())

?

print(name.startswith('al'))

?

print(name.endswith('X'))

?

print(name.replace('l','p'))

print(name.split('l'))

print(name.upper())

print(name.capitalize())

print(name[1])

print(name[:3])

print(name[3:])

print(name.index('e'))

print(name[:-1])?

有列表data=[‘alex’,49,[1900,3,18]],分別取出列表中的名字,年齡,出生的年,月,日賦值給不同的變量?

data=['alex',49,[1900,3,18]]

name = data[0]

age = data[1]

birth = data[2]

print("名字是{0}年齡是{1}出生年月是{2}".format(name,age,birth))?

用列表模擬隊列(隊列是先進先出,類似于自動扶梯)?

dui = [1,2,3,4,5,6]

dui.insert(len(dui),'ll')

print(dui)

dui.pop(0)

print(dui)?

用列表模擬堆棧(堆棧先進后出,類似于喝酒喝吐了)?

zhan = [1,2,3,4,5,6]

zhan.insert(len(zhan),'ll')

print(zhan)

zhan.pop()

print(zhan)

?

有如下列表,請按照年齡排序(涉及到匿名函數)?

l=[

? ? {'name':'alex','age':84},

? ? {'name':'oldboy','age':73},

? ? {'name':'egon','age':18},

]

?

l.sort(key=lambda item:item['age'])

print(l)

?

1 有如下值集合 [11,22,33,44,55,66,77,88,99,90…],將所有大于 66 的值保存至字典的第一個key中,將小于 66 的值保存至第二個key的值中? 即: {‘k1’: 大于66的所有值, ‘k2’: 小于66的所有值}?

l = [11,22,33,44,55,66,77,88,99,90,50,40,100]

?

dic = {'k1':[],'k2':[]}

for num in l:

? ? if num > 66:

? ? ? ? dic['k1'].append(num)

? ? else:

? ? ? ? dic['k2'].append(num)

?

print(dic)?

2 統計s=’hello alex alex say hello sb sb’中每個單詞的個數? 結果如:{‘hello’: 2, ‘alex’: 2, ‘say’: 1, ‘sb’: 2}? s=’hello alex alex say hello sb sb’? ll = s.split() # 以空格區分? 集合去重實現#? res = set(ll) # 去重? dic = dic.fromkeys(res) #初始化字典? for k in res:? dic[k] = ll.count(k) #填入數據? print(dic)? 字典的setdefault方法實現#? dic = {}? for k in ll:? dic.setdefault(k,ll.count(k))? print(dic)?

1. 有列表l=[‘a’,’b’,1,’a’,’a’],列表元素均為可hash類型,去重,得到新列表,且新列表無需保持列表原來的順序?

l=['a','b',1,'a','a']

new = set(l)

print(new)?

2.在上題的基礎上,保存列表原來的順序?

l=['a','b',1,'a','a']

new = set()

res = []

for d in l:

? ? if d not in new:

? ? ? ? new.add(d)

? ? ? ? res.append(d)

print(res)?

3.去除文件中重復的行,肯定要保持文件內容的順序不變?

?

file = open('C:\Users\liuliangliang\Desktop\UserLoginServiceImplTest.java','r')

file = file.readlines()

s = set()

res = []

for line in file:

? ? if line in file:

? ? ? ? print(line)

? ? ? ? if line? not in s:

? ? ? ? ? ? s.add(line)

? ? ? ? ? ? res.append(line)

?

write = open('C:\Users\liuliangliang\Desktop\UserLoginServiceImplTest','w')

write.writelines(res)?

4.有如下列表,列表元素為不可hash類型,去重,得到新列表,且新列表一定要保持列表原來的順序?

l=[

? ? {'name':'egon','age':18,'sex':'male'},

? ? {'name':'alex','age':73,'sex':'male'},

? ? {'name':'egon','age':20,'sex':'female'},

? ? {'name':'egon','age':18,'sex':'male'},

? ? {'name':'egon','age':18,'sex':'male'},

]

?

s = set()

res = []

?

for i in l:

? ? val = (i['name'],i['age'],i['sex'])

? ? if val not in s:

? ? ? ? print(val)

? ? ? ? s.add(val)

? ? ? ? res.append(i)

print(res)

print(s)?

文件a.txt內容:每一行內容分別為商品名字,價錢,個數,求出本次購物花費的總錢數?

apple 10 3?

tesla 100000 1?

mac 3000 2?

lenovo 30000 3?

chicken 10 3?

import os

?

### 獲取當前文件路徑

pwd = os.getcwd()

### 得到存儲用戶信息的文件路徑

filedir = pwd + '\qingdan'

### 判斷信息文件是否存在,存在即取出并轉換成字典類型數據,否則提示文件不存在退出

if os.path.exists(filedir):

? ? wp = open(filedir, 'r',encoding='utf-8')

? ? sett = wp.readlines()

? ? print(sett)

? ? wp.close()

else:

? ? print("文件不存在!")

? ? exit()

last = 0

for i in sett:

? ? res = i.split()

? ? count = int(res[1])*int(res[2])

? ? last = last + count

print(last)

?

需求:?

用戶名和密碼存放于文件中,格式為:egon|egon123? 啟動程序后,先登錄,登錄成功則讓用戶輸入工資,然后打印商品列表,失敗則重新登錄,超過三次則退出程序? 允許用戶根據商品編號購買商品? 用戶選擇商品后,檢測余額是否夠,夠就直接扣款,不夠就提醒? 可隨時退出,退出時,打印已購買商品和余額?

?

?

import json

import os

?

# 獲取當前文件路徑

pwd = os.getcwd()

# 得到存儲用戶信息的文件路徑

filedir = pwd + '\dic'

listdir =pwd + '\list'

# 判斷信息文件是否存在,存在即取出并轉換成字典類型數據,否則提示文件不存在退出

if os.path.exists(filedir) and os.path.exists(listdir):

? ? wp = open(filedir, 'r')

? ? sett = wp.read()

? ? dic_user = json.loads(sett)

? ? wp.close()

? ? sp = open(listdir,'r')

? ? shop = sp.read()

? ? dic_product = json.loads(shop)

? ? sp.close()

else:

? ? print("文件不存在!")

? ? exit()

?

Tag = True

while Tag:

?

? ? name = input("請輸入用戶名:")

? ? # 判斷用戶名是否存在于文件中

? ? if name not in dic_user.keys():

? ? ? ? print("用戶不存在!")

? ? ? ? continue

? ? passwd = input("請輸入用戶密碼:")

? ? # 判斷用戶名密碼是否正確

? ? if name in dic_user.keys() and passwd == dic_user.get(name).get('passwd'):

? ? ? ? list_info = [{"username": name}]

? ? ? ? cmd = input("輸入你的工資")

? ? ? ? last = int(cmd)

? ? ? ? while Tag:

?

? ? ? ? ? ? print(dic_product)

? ? ? ? ? ? # cap,num = input("___輸入您想要購買的物品編號和個數以空格分開:如'001 2'").split()

? ? ? ? ? ? cap = input("輸入您所購買的物品編碼:").strip()

?

? ? ? ? ? ? if cap? not in dic_product :

? ? ? ? ? ? ? ? print("請輸入正確的物品編碼")

? ? ? ? ? ? ? ? continue

?

? ? ? ? ? ? num = input("輸入您所購買物品的數量:").strip()

?

? ? ? ? ? ? if cap? not in dic_product or not num.isdigit():

? ? ? ? ? ? ? ? print("請輸入正確的物品編碼或購買數!")

? ? ? ? ? ? ? ? continue

?

? ? ? ? ? ? account = int(dic_product[cap][1]) * int(num)

? ? ? ? ? ? if? account <= last:

? ? ? ? ? ? ? ? last = last - account

?

? ? ? ? ? ? ? ? list_info.append({"product":dic_product[cap],"num":num})

? ? ? ? ? ? ? ? quit = input("購買成功,退出輸入q,繼續輸入y")

? ? ? ? ? ? ? ? if quit == 'q':

? ? ? ? ? ? ? ? ? ? Tag = False

? ? ? ? ? ? ? ? ? ? continue

? ? ? ? ? ? ? ? else:

? ? ? ? ? ? ? ? ? ? continue

? ? ? ? ? ? else:

?

? ? ? ? ? ? ? ? addin = input("余額不足!充值輸入y,退出輸入q")

? ? ? ? ? ? ? ? if addin == 'y':

? ? ? ? ? ? ? ? ? ? add = input("輸入充值金額:").strip()

? ? ? ? ? ? ? ? ? ? last = int(last) + int(add)

? ? ? ? ? ? ? ? ? ? print("余額為%d" %last)

? ? ? ? ? ? ? ? if addin == 'q':

? ? ? ? ? ? ? ? ? ? Tag =False

? ? ? ? ? ? ? ? ? ? continue

?

? ? ? ? list_info.append({"last_money": last})

? ? ? ? for i in list_info:

? ? ? ? ? ? print(i)

? ? ? ? continue

? ? else:

? ? ? ? if name in dic_user.keys():

? ? ? ? ? ? print("用戶名存在,密碼錯誤")

?

? ? ? ? ? ? dic_user[name]['count'] += 1

? ? ? ? ? ? if dic_user[name]['count'] == 3:

? ? ? ? ? ? ? ? print("輸入錯誤三次,退出程序")

? ? ? ? ? ? ? ? Tag = False

?

input(" ")?

要求:?

打印省、市、縣三級菜單? 可返回上一級? 可隨時退出程序?

import json

import os

?

# 獲取當前文件路徑

pwd = os.getcwd()

# 得到存儲用戶信息的文件路徑

filedir = pwd + '\www'

# 判斷信息文件是否存在,存在即取出并轉換成字典類型數據,否則提示文件不存在退出

if os.path.exists(filedir):

? ? wp = open(filedir, 'r',encoding='utf-8')

? ? sett = wp.read()

? ? data = json.loads(sett)

? ? wp.close()

else:

? ? print("文件不存在!")

? ? exit()

# 定義一個字典類型,存放修改后的字典

diction = data

# 定義一個列表類型,存放修改后的字典

listion = [data]

?

while True:

# 當字典為空時,提示沒有下級,顯示上一層內容

? ? if diction == {}:

? ? ? ? print("沒有下級了!")

? ? ? ? diction = listion[-1]

? ? ? ? listion.pop()

?

? ? for key in diction:

? ? ? ? print(key,end=' |')

? ? agent = input("\n輸入上述名稱查詢,輸入r返回上一層,輸入q退出:")

# 如果輸入信息存在當前字典中,將當前的字典追加進入列表,將當前字典轉換成下級字典

? ? if agent in diction:

? ? ? ? listion.append(diction)

? ? ? ? diction = diction[agent]

# 如果輸入信息是r, 判斷列表為空時提示沒有上一級,不為空返回上一級,當前字典轉換成上一級字典

? ? elif agent == 'r':

? ? ? ? if len(listion) == 0:

? ? ? ? ? ? print("沒有上一級了!")

? ? ? ? else:

? ? ? ? ? ? diction = listion[-1]

? ? ? ? ? ? listion.pop()

# 如果輸入信息是q,退出程序

? ? elif agent == 'q':

? ? ? ? break

? ? else:

? ? ? ? print("輸入有誤,重新輸入")

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/540584.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/540584.shtml
英文地址,請注明出處:http://en.pswp.cn/news/540584.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

組合數據類型練習,英文詞頻統計實例上

1、字典實例&#xff1a;建立學生學號成績字典&#xff0c;做增刪改查遍歷操作。 建立&#xff1a; d{0001:99,0003:89,0004:98,0005:100,0006:78} 增&#xff1a;d[0002]79 刪&#xff1a;d.pop(0001) 改&#xff1a;d[0004]100 查&#xff1a;print(d[0002]) 遍歷操作&#x…

茱莉亞分形_茱莉亞的NaN Constant

茱莉亞分形Julia| NaN / Nan64常數 (Julia | NaN/Nan64 Constant) Nan / Nan64 is a constant of the Float64 type in Julia programming language, it represents "not-a-number" value. Nan / Nan64是Julia編程語言中Float64類型的常量&#xff0c;它表示“非數字…

[轉載] Python3 數組

參考鏈接&#xff1a; Python中的Array | 數組1(簡介和功能) 一、list和array的區別 Python的數組通過Numpy包的array實現。 Python里二者最大的區別是&#xff0c;list可以存儲不同類型的數據&#xff0c;而array只能存儲相同類型的數據。 import numpy #直接定義 a […

201671010128 2017-09-24《Java程序設計》之繼承

1.繼承的概念及理解&#xff1a; 繼承是java面向對象編程技術的一塊基石&#xff0c;因為它允許創建分等級層次的類。繼承就是子類繼承父類的特征和行為&#xff0c;使得子類對象&#xff08;實例&#xff09;具有父類的實例域和方法&#xff0c;或子類從父類繼承方法&#xff…

紫外線的形式是什么?

紫外線&#xff1a;紫外線 (UV: Ultraviolet) UV is an abbreviation of Ultraviolet. In RO water purifiers, the bacteria or germs which are present in the water cannot get killed by reverse osmosis process but this process can banish the dissolved solids and i…

[js高手之路] html5 canvas系列教程 - 掌握畫直線圖形的常用API

我們接著上文[js高手之路] html5 canvas系列教程 - 認識canvas以及基本使用方法繼續. 一、直線的繪制 cxt.moveTo( x1, y1 )&#xff1a; 將畫筆移動到x1, y1這個點 cxt.lineTo( x2, y2 )&#xff1a;將畫筆從起點開始畫直線&#xff0c;一直畫到終點坐標( x2, y2 ) cxt.stroke…

金礦問題

Description: 描述&#xff1a; This is a standard interview problem featured in interview coding rounds of Amazon, Flipkart. 這是亞馬遜Flipkart的采訪編碼回合中的標準采訪問題。 Problem statement: 問題陳述&#xff1a; Given a gold mine of n*m dimensions, e…

[轉載] python中的數組類型及特點

參考鏈接&#xff1a; Python中的Array | 數組2(簡介和功能) 名稱 表示方法示例 是否有序 函數方法&#xff08;增刪等&#xff09; 特點 List 類型表示&#xff1a;L L [Adam, 95.5, Lisa, 85] 有序 增加&#xff1a;&#xff08;1&#xff09;L.append(Paul),增加…

puppet

Puppet前期環境&#xff08;網絡、解析、yum源、NTP&#xff09;在上一章節已經準備就緒&#xff0c;接下來我們就開始安裝Puppet了&#xff0c;安裝Puppet其實很簡單&#xff0c;官方已經提供了yum源&#xff0c;只需要自己將所需要的安裝包下載下來然后做成本地yum源即可使用…

[轉載] 【數學問題】利用python求解表達式

參考鏈接&#xff1a; Python 變量 &#xff5c;表達式 &#xff5c;條件和函數 有時候我們會遇到一些很復雜的表達式&#xff0c;或者想要求解某個表達式&#xff0c;但是手動計算的話不但耗時還費精力&#xff0c;我們能不能利用計算機來幫助我們進行計算呢&#xff1f; 1…

cesium廣告牌_公路廣告牌

cesium廣告牌Description: 描述&#xff1a; This is a standard dynamic programing problem of finding maximum profits with some constraints. This can be featured in any interview coding rounds. 這是在某些約束條件下找到最大利潤的標準動態編程問題。 這可以在任何…

你和大牛差了啥

mmp。無時無刻不在想和大牛差在哪里了。別人為什么可以那么牛逼而你tmd那么菜&#xff01;整個人頓時都頹廢了。啥事兒不想干。后來想了想感情就是他比較黑吧。

[轉載] python數組的使用

參考鏈接&#xff1a; Python中整數的最大可能值是多少&#xff1f; 原文地址為&#xff1a; python數組的使用 python數組的使用 python數組的使用 2010-07-28 17:17 1、Python的數組分三種類型&#xff1a; (1) list 普通的鏈表&#xff0c;初始化后可以通過特定方法…

scala中循環守衛_Scala中的循環

scala中循環守衛Scala中的循環 (Loops in Scala) In programming, many times a condition comes when we need to execute the same statement or block of code more than one time. It could be difficult to write the same code multiple times, so programing language d…

50個必備基礎命令

1.tar創建一個新的tar文件$ tar cvf archive_name.tar dirname/解壓tar文件$ tar xvf archive_name.tar查看tar文件$ tar tvf archive_name.tar2. grep在文件中查找字符串(不區分大小寫)$ grep -i "the" demo_file輸出成功匹配的行&#xff0c;以及該行之后的三行$ g…

NM的完整形式是什么?

NM&#xff1a;無消息 (NM: No Message) NM is an abbreviation of "No Message". NM是“無消息”的縮寫。 It is an expression, which is commonly used in the Gmail platform. It is also written as N/M or n/m or *n/m*. It is written in the subject of the…

[轉載] python中全局變量和局部變量解析

參考鏈接&#xff1a; Python中的全局變量和局部變量 python函數中可以訪問全局變量但是不能給全局變量賦值&#xff0c;除非進行顯式聲明global a 比如定義了全局變量 a 在函數my_fun()中可以直接訪問a的值&#xff0c;而不需要global全局變量申明。下圖為上面代碼運行輸出 …

【iCore4 雙核心板_FPGA】例程十六:基于雙口RAM的ARM+FPGA數據存取實驗

實驗現象&#xff1a; 核心代碼&#xff1a; int main(void) {/* USER CODE BEGIN 1 */int i;int address,data;char error_flag 0;char receive_data[50];char buffer[8];char *p;/* USER CODE END 1 *//* MCU Configuration-----------------------------------------------…

[轉載] Python中TFTP的理解

參考鏈接&#xff1a; Python中的打包pack和拆包unpack參數 Num01–>TFTP協議介紹 TFTP&#xff08;Trivial File Transfer Protocol,簡單文件傳輸協議&#xff09; 是TCP/IP協議族中的一個用來在客戶端與服務器之間進行簡單文件傳輸的協議 特點&#xff1a; 1,簡單 2…

gn fast-gn_GN的完整形式是什么?

gn fast-gnGN&#xff1a;晚安 (GN: Good Night) GN is an abbreviation of "Good Night". GN是“ Good Night”的縮寫 。 It is an expression, which is commonly used in messaging or chatting on social media networking sites like Facebook, Yahoo Messenge…