Python教程

Python基础100题打卡Day11

本文主要是介绍Python基础100题打卡Day11,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

题目三十八

对于给定的元组(1,2,3,4,5,6,7,8,9,10),编写一个程序,在一行中打印前半值,在一行中打印最后一半值。

代码实现

方法一:利用循环对元组数据进行输出

tpl = (1,2,3,4,5,6,7,8,9,10)

for i in range(0,5):
    print(tpl[i],end= ' ')
print()
for i in range(5,10):
    print(tpl[i],end= ' ')

方法二:利用列表中的.append()函数将元组数据添加到列表中,之后进行输出

tpl = (1,2,3,4,5,6,7,8,9,10)
lst1, lst2 = [], []
for i in range(0,5):
    lst1.append(tpl[i])
print(lst1,end= '\n')
for i in range(5,10):
    lst2.append(tpl[i])
print(lst2)

方法三:元组切片复制

tpl = (1,2,3,4,5,6,7,8,9,10)
lt = int(len(tpl)/2)
print(tpl[:lt],end='\n')
print(tpl[lt:])

方法四:.format()函数规定输出样式,range(初始点,结束点,步长)确定输出位置

print("初始元组:", tpl)
[
    print("分割元组 :{List}".format(List=tpl[x : x + 5]))
    for x in range(0, len(tpl), 5)
]

运行结果

输出结果:

(1, 2, 3, 4, 5)
(6, 7, 8, 9, 10)

题目三十九

编写一个程序来生成和打印另一个元组,其值为给定元组中的偶数(1,2,3,4,5,6,7,8,9,10)。

代码实现

方法一:利用循环对元组数据进行输出

tpl = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
tpl1 = tuple(i for i in tpl if i%2 == 0 )
print(tpl1)

方法二:lambda一句话函数

tpl = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
tpl1 = tuple(
    filter(lambda x: x%2 == 0,tpl) #lambda函数返回值为True内容
)#filter去除返回值为False的内容
print(tpl1)

运行结果

输出结果:

(2, 4, 6, 8, 10)

题目四十

编写一个接受字符串作为输入的程序,如果字符串是“Yes”或“YES”或“yes”,则打印“Yes”,否则打印“No”。

代码实现

方法一:使用if条件语句对输入进行检测

text = input("请输入:")
if text == 'YES' or text == 'Yes' or text == 'yes':
    print('Yes')
else:
    print('No')

方法二:.join()函数设置条件

text = input("请输入")
print_text = " ".join(
    ['Yes' if text == 'YES' or text == 'Yes' or text == 'yes' else 'No']
)
print(str(print_text))

运行结果

输出结果:

请输入y
No

题目四十一

编写一个可map()的程序,列出元素为[1,2,3,4,5,6,7,8,9,10]中元素的平方列表。

代码实现

方法:

lst = [1,2,3,4,5,6,7,8,9,10]
doublelst = map(lambda x: x**2 , lst)
print(list(doublelst))

注意:map()函数输出的是一个集合,需要对其的输出进行转换

运行结果

输出结果:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

题目四十二

编写一个程序,它可以map()和filter(),以在[1,2,3,4,5,6,7,8,9,10]中列出元素为偶数平方的列表。

代码实现

方法:利用map()对列表进行运算,以及filter()去除False值得功能

def even(x):
    return x%2 == 0

def square(x):
    return x**2

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
lst1 = list(map(square, filter(even,lst)))
print(lst1)

注意:map()函数输出的是一个集合,需要对其的输出进行转换

运行结果

输出结果:

[4, 16, 36, 64, 100]

题目四十三

编写一个程序,该程序可以筛选()来生成元素偶数介于1和20之间的列表(两者都包括在内)。

代码实现

def even(x):
    return x%2 == 0

Num = filter(even , range(1,21))
print(list(Num))

注意:map()函数输出的是一个集合,需要对其的输出进行转换

运行结果

输出结果:

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
这篇关于Python基础100题打卡Day11的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!