Frage

  1. Have the following line of code, which reads pairs of words from a file, splits them, and returns a tuple, where the first index of each tuple is either the first or second word. For example, a Bob, Smith will translate to [(Bob, Smith)] and [(Smith, Bob)] respectively. I map this to every pair in g.readlines().

    Was wondering if it was at all possible to pass a second parameter flip = True, into a more general word_flip() function which can be used with map?

    first_word_is_first = map(first_second_split, g.readlines())
    
    first_word_is_second = map(second_first_split, g.readlines())
    
  2. A random question regarding a more functional approach, If I am given a string, and I would like to partition that string based on the attribute of each word (ie. Alex Smith AGE 35 420) is there a more functional way approach such a problem besides iterating through string.split() and dividing the line into str variables, name, age, room_number or using regex? Is it at all possible to use map, filter, or itertools? Would preferably pass through the string once.

War es hilfreich?

Lösung

  1. Yes, you could use a functools.partial to add additional arguments to your function when using it in a map().

    from functools import partial
    first_word_is_first = map(partial(word_flip, flip=False), g.readlines())
    first_word_is_second = map(partial(word_flip, flip=True), g.readlines())
    

    It'll be easier to use a list comprehension though:

    first_word_is_first = [word_flip(l, flip=False) for l in g.readlines()]
    first_word_is_second = [word_flip(l, flip=True) for l in g.readlines()]
    
  2. The way your string is structured (spaces both between fields and inside of the fields) you'll have to use a method like a regex or dedicated function to split out the fields.

Andere Tipps

for 2:

name, surname, n, age, room = 'Alex Smith AGE 35 420'.split()

return multiple results from method call.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top