欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

class Python Data Science Toolbox

程序员文章站 2024-01-30 20:13:28
...

map函数的使用:


  • In the map() call, pass a lambda function that concatenates the string '!!!' to a string item; also pass the list of strings, spells. Assign the resulting map object to shout_spells.
  • Convert shout_spells to a list and print out the list.

# Create a list of strings: spells
spells = ["protego", "accio", "expecto patronum", "legilimens"]


# Use map() to apply a lambda function over spells: shout_spells
shout_spells = map(lambda item : item + "!!!", spells)


# Convert shout_spells to a list: shout_spells_list
shout_spells_list = list(shout_spells)


# Convert shout_spells into a list and print it
print(shout_spells_list)



filter 函数的使用:


  • In the filter() call, pass a lambda function and the list of strings, fellowship. The lambda function should check if the number of characters in a string member is greater than 6; use the len() function to do this. Assign the resulting filter object to result.
  • Convert result to a list and print out the list.

# Create a list of strings: fellowship
fellowship = ['frodo', 'samwise', 'merry', 'aragorn', 'legolas', 'boromir', 'gimli']


# Use filter() to apply a lambda function over fellowship: result
result = filter(lambda member : len(member) > 6, fellowship)


# Convert result to a list: result_list
result_list = list(result)


# Convert result into a list and print it
print(result_list)


reduce函数的使用:
# Define gibberish
def gibberish(*args):
    """Concatenate strings in *args together."""
    hodgepodge = ''
    for word in args:
        hodgepodge += word
    return hodgepodge

gibberish() simply takes a list of strings as an argument and returns, as a single-value result, the concatenation of all of these strings. In this exercise, you will replicate this functionality by using reduce() and a lambda function that concatenates strings together.

Instructions

  • Import the reduce function from the functools module.
  • In the reduce() call, pass a lambda function that takes two string arguments item1 and item2 and concatenates them; also pass the list of strings, stark. Assign the result to result. The first argument to reduce() should be the lambda function and the second argument is the list stark.


# Import reduce from functools
from functools import reduce


# Create a list of strings: stark
stark = ['robb', 'sansa', 'arya', 'eddard', 'jon']


# Use reduce() to apply a lambda function over stark: result
result = reduce(lambda item1,item2 : item1 + item2, stark)


# Print the result
print(result)




相关标签: python