python输入输出特殊处理

本文介绍了Python中的各种基本数据结构如列表、二维列表、ASCII码、字典、集合、字符串的处理方法,以及查询、文件读取、深浅拷贝和itertools模块中的组合与排列功能。
摘要由CSDN通过智能技术生成

输出

需要满足输出一行后,再输出一行,行中每个元素用空格隔开

length = len(tri)
tmp = []
for i in range(len(tri)):
    tmp = tri[i]
    for j in range(len(tri[i])):
        print(tmp[j],end=' ')
    print()

输入p

一次性输入6个数字到列表中,并且输入的每个数据用空格分开

# 输入6个数字,每个数字用空格分开
numbers = input("请输入6个数字(用空格分隔): ").split()

# 将输入的字符串转换为整数类型的列表
numbers = [int(num) for num in numbers]

# 打印列表
print("输入的数字列表:", numbers)

二维列表

# 使用循环和输入函数输入二维列表
rows = 3 # 行
cols = 3 # 列
my_list = []

for i in range(rows):
    row = []
    for j in range(cols):
        num = int(input(f"Enter element at position ({i}, {j}): "))
        row.append(num)
    my_list.append(row)
    
# 获得列表每一列的数据
data = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
a = list(zip(*data))
>>> [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

ASCII码

# 输出ASCII码
num = ord('a')

# ASCII码转字符
print(chr(num))

字典

dict.get(key, default=None)
#返回指定键的值,如果值不在字典中返回default值

dict.items()
#以列表返回可遍历的(键, 值) 元组数组

dict.keys()
#以列表返回一个字典所有的键

dict.values()
#以列表返回字典中的所有值

pop(key[,default])
#删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。

集合

# 集合的好处就是无序性 即{1,2,3} == {2,1,3}
# 往集合中添加元素
thisset = set(("Google", "Runoob", "Taobao"))
thisset.add("Facebook")

# 删除集合中的某个元素
thisset.remove("Taobao")

字符串

str.capitalize() # 把字符串第一个字符大写
str.count(str, beg=0, end=len(string)) #返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数
str.swapcase() # 翻转str中的大小写
str.upper() # 把小写全部改为大写
str.casefold() # 把大写全部改为小写

查询方法

# 如果不记得列表/字典..的方法
dir(list)

# 如果不记得这个方法的用法
help(obj.method)
help(list.count)

文件读取

with open("2020.txt") as fp:
    for a in fp.readlines():
        nums.append(list(a.strip())) #a.strip() 是Python中用于移除字符串两侧空格(包括换行符、制表符等空白字符)的方法

深浅拷贝

# 浅拷贝
a = [1,2,3]
b = a.copy()
a.append(4)
a
>>>[1,2,3,4]
b
>>>[1,2,3,4]

# 深拷贝
a = [1,2,3]
import copy
b = copy.deepcopy(a)
a.append(4)
a
>>>[1,2,3,4]
b
>>>[1,2,3]

itertools模块

这个模块的本质是一个迭代器

import itertools

# 双组合迭代器
# 在传递的两个参数里面,前面和后面相组合
for i in itertools.product([1,2,3],[4,5,6]):
    print(i)
ans:
(1, 4)
(1, 5)
(1, 6)
(2, 4)
(2, 5)
(2, 6)
(3, 4)
(3, 5)
(3, 6)


# 排列数
# 输出给定元素的排列数
for i in itertools.permutations('abc'):
	print(i)
ans:
('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')
# 还可以有第二个参数
for i in itertools.permutations('abc',2):
    print(i)
ans:
('a', 'b')
('a', 'c')
('b', 'a')
('b', 'c')
('c', 'a')
('c', 'b')


# 组合数
import itertools
for i in itertools.combinations('1234',2):
    print(i)

('1', '2')
('1', '3')
('1', '4')
('2', '3')
('2', '4')
('3', '4')


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值