Python基礎之元組和字典


一、元組:

  1、定義:

  

    內存圖:

    

  2、基本操作

    

  3、元組作用:

  

  4、元組基礎知識代碼

  

# 1. 創建空元組
t01 = ()
t02 = tuple()

# 2. 創建具有默認值的元組
t01 = (1,2,3)
t01 = tuple("abcd")
t01 = (1,2,[4,5])
print(t01)

# 修改
# t01[2] = 100  元組元素不能修改,報錯
t01[2][0] = 100 # 修改的是元素第三個元素(列表)的元素.

# 3. 獲取元素(索引 / 切片)
print(t01[:2])

# 獲取元組所有元素
for item in t01:
    print(item)

# 倒序獲取元組所有元素
for i in range(len(t01)-1, -1,-1):
    print(t01[i])


t02 = ("a","b")
l02 = ["a","b"]

t03 = t02
l03 = l02

t02 += ("c","d") # 創建了新元組對象,改變了t02存儲的地址.
l02 += ["c","d"] # 將["c","d"]追加到原列表中.

print(t02) # ('a', 'b', 'c', 'd')
print(t03) # ('a', 'b')
print(l03) # ['a', 'b', 'c', 'd']


# 如果元組只有一個元素,必須多寫一個逗號,否則視為普通對象,不是元組對象.
t04 = (1,)
print(t04)

  5、實例:

    (1)根據月份,計算天數

    

# month = int(input("請輸入月份:"))
# if month < 1 or month > 12:
#     print("輸入有誤")
# elif month == 2:
#     print("28天")
# # elif month == 4 or month == 6 or month == 9 or month == 11:
# elif month in (4,6,9,11):
#     print("30天")
# else:
#     print("31天")

month = int(input("請輸入月份:"))
if month < 1 or month > 12:
    print("輸入有誤")
else:
    # 將每月的天數,存入元組.
    day_of_month = (31,28,31,30,31,30,31,31,30,31,30,31)
    print(day_of_month[month - 1])

    (2)在控制台中輸入月,日,計算這是一年的第幾天。例如輸入3月5日,計算天數為?

    

#方法一
# month = int(input("請輸入月份:"))
# day = int(input("請輸入天:"))
# day_of_month = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
# result = 0
# # 累加前幾個月
# for i in range(month - 1):
#     result += day_of_month[i]
# # 累加當月
# result += day
# print(result)


#方法二
month = int(input("請輸入月份:"))
day = int(input("請輸入天:"))
day_of_month = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
# 累加前幾個月
result = sum(day_of_month[:month - 1])
# 累加當月
result += day
print(result)

二、字典:

  1、定義

    

      內存圖:

      

  2、基本操作:

    

  3、字典推導式

    

  4、字典VS列表

    

  5、字典基礎代碼

    

# 創建空字典
d01 = {}
d02 = dict()

d01 = {"a":"A","b":"B"}
# d01 = dict("ab") # 分不清key  value
d01 = dict([(1,2),(3,4)]) # {1: 2, 3: 4}


# 第一次增加
d01["c"] = "C"
# 第二次修改
d01["c"] = "CC"

# 讀取元素(如果不存在則異常)
# 建議:在字典中讀取元素,先判斷存在,在進行讀取.
if "d" in d01:
    print(d01["d"])

print(d01)
# 刪除
del d01["c"]
print(d01)

# 獲取字典中所有元素:
for key in d01:
    print(key)
    print(d01[key])

# 獲取字典中所有記錄(元組)
for item in d01.items():
    print(item[0]) # key
    print(item[1]) # value

for k,v in d01.items():
    print(k) # key
    print(v) # value

# 獲取所有鍵
for k in d01.keys():
    print(k)

# 獲取所有值
for v in d01.values():
    print(v)

  6、實例:

    (1)在控制台中錄入一個字符串,打印這個字符串中的字符以及各字符出現的次數

      

str_input = input("請輸入一個字符串:")
# key: 字符   value:次數
result = {}
# (1)逐一判斷字符,出現的次數.
for item in str_input:
    # (2)如果沒有統計過該字符串
    if item not in result:
        result[item] = 1
    else:
        # (3)否則,次數增加
        # result[item] = result[item] + 1
        result[item] += 1

print(result)

    (2)給定一個列表["張三豐","無忌","趙敏"] ,以字典的形式輸出鍵為列表元素,值為列表元素長度,形如:{"張三豐":3,"無忌":2,"趙敏",2}

      

#方法一
list01 = ["張三豐", "無忌", "趙敏"]
dict01 = {}
for item in list01:
    dict01[item] = len(item)


#方法二
dic02 = {item: len(item) for item in list01}
print(dic02)

    (3)# 練習:
       ["張三豐", "無忌", "趙敏"]
       [101, 102, 103]
        (1) 根據兩個列表形成一個字典:key姓名,value房間號
        (2) 將字典的鍵與值進行翻轉.即:key房間號,value姓名

        

list01 = ["張三豐", "無忌", "趙敏"]
list02 = [101, 102, 102]
# 循環方式
# dict01 = {}
# for i in range(len(list01)):
#     dict01[list01[i]] = list02[i]

# 字典推導式
dic02 = {list01[i]: list02[i] for i in range(len(list01))}
print(dic02)


# 循環方式(值不重復)
# dic03 = {}
# for key,value in dic02.items():
#     dic03[value] = key

# 字典推導式(值重復)
# {101: '張三豐', 102: '趙敏'}   張無忌與趙敏同居,導致key重復,無忌被覆蓋.
dic03 = {value: key for key, value in dic02.items()}
print(dic03)

#[(102, '無忌'), (101, '張三豐'), (102, '趙敏')],即值重復時,用列表推導式
list03 = [(value,key) for key, value in dic02.items()]
print(list03)

     (4)練習4:在控制台中錄入5個學生信息(姓名/年齡/性別)

      

# 4. 在控制台中錄入5個學生信息(姓名/年齡/性別)
# 數據結構:列表中嵌套字典
# [
#     {
#         "name":xx,
#         "age":xx,
#         "sex":xx,
#     },
#     {
#         "name":xx,
#         "age":xx,
#         "sex":xx,
#     }
#     .......
# ]

list_student_info = []
for i in range(2):
    # 每次循環創建一個新字典表示一個新學生
    dict_student = {}
    dict_student["name"] = input("請輸入姓名:")
    dict_student["age"] = int(input("請輸入年齡:"))
    dict_student["sex"] = input("請輸入性別:")
    # 向學生列表追加學生信息
    list_student_info.append(dict_student)


# 獲取所有學生信息
for dict_stu in list_student_info:
    for key,value in dict_stu.items():
        print("%s -- %s"%(key,value))

    (5)練習5:猜拳,規則:系統隨機出拳,在控制台中循環猜測.

    

"""
 猜拳
  規則:系統隨機出拳,在控制台中循環猜測.
  提示:(1)將勝利的策略存入容器
              (
                  ("石頭","剪刀"),
                  ("剪刀","布"),
                  ("布","石頭")
              )
       (2) 將用戶猜的拳與系統出拳形成一個元組
"""

import random


# 勝利策略
wins = (
    ("石頭", "剪刀"),
    ("剪刀", ""),
    ("", "石頭")
)
# 將用戶猜的拳與系統出拳形成一個元組
user_input_index = int(input("請輸入整數(0表示石頭,1表示剪刀,2表示布):"))
items = ("石頭","剪刀","")
user_input_item = items[user_input_index]

sys_input_index = random.randint(0,2)
sys_input_item = items[sys_input_index]

# 邏輯處理
if user_input_item == sys_input_item:
    print("平局")
elif (user_input_item,sys_input_item) in wins:
    print("贏啦")
else:
    print("輸啦")

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM