Question 38
对于给定的元组(1,2,3,4,5,6,7,8,9,10),编写一个程序,在一行中打印前半部分值,在一行中打印后半部分值。
方法1:
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 = ' ')
方法2:
tup = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
lt = int(len(tup)/2)
print(tup[:lt], tup[lt:])
方法3:
tup = [i for i in range(1, 11)]
print(f'{tuple(tup[:5])} \n{tuple(tup[5:])}')
Question 39
编写一个程序来生成并打印另一个元组,其值是给定元组中的偶数(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)
tpl = (1,2,3,4,5,6,7,8,9,10)
tpl1 = tuple(filter(lambda x : x%2==0,tpl)) # Lambda function returns True if found even element.
# Filter removes data for which function returns False
print(tpl1)
Question 40
写一个程序,它接受一个字符串作为输入,如果字符串是“yes”或“YES”或“Yes”,则打印“Yes”,否则打印“No”。
text = input("Please type something. --> ")
if text == "yes" or text == "YES" or text == "Yes":
print("Yes")
else:
print("No")
input = input('Enter string:')
output = ''.join(['Yes' if input == 'yes' or input =='YES' or input =='Yes' else 'No' ])
print(str(output))
Question 41
写一个程序,可以使用map()来创建一个列表,其元素是[1,2,3,4,5,6,7,8,9,10]中元素的平方。
li = [1,2,3,4,5,6,7,8,9,10]
squaredNumbers = map(lambda x: x**2, li) # returns map type object data
print(list(squaredNumbers)) # converting the object into list
def sqrs(item):
return item ** 2
lst = [i for i in range(1, 11)]
print(list(map(sqrs, lst)))
Question 42
编写一个程序,利用map()和filter()生成一个元素为[1,2,3,4,5,6,7,8,9,10]中偶数的平方的列表。文章来源:https://www.toymoban.com/news/detail-440374.html
def even(x):
return x%2==0
def squer(x):
return x*x
li = [1,2,3,4,5,6,7,8,9,10]
li = map(squer,filter(even,li)) # first filters number by even number and the apply map() on the resultant elements
print(list(li))
def even(item):
if item % 2 == 0:
return item**2
lst = [i for i in range(1, 11)]
print(list(filter(lambda j: j is not None, list(map(even, lst)))))
Question 43
编写一个程序,它可以使用filter()来创建一个列表,其中的元素是1到20之间的偶数(包括两者)。文章来源地址https://www.toymoban.com/news/detail-440374.html
def even(x):
return x%2==0
evenNumbers = filter(even, range(1,21))
print(list(evenNumbers))
到了这里,关于100+Python挑战性编程练习系列 -- day 11的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!