简体   繁体   中英

How to assign the for loop values in variable in one line

So I have the following example of code; simultaneously iterates over multiple sequences combined with enumerate, assigning the values to tuple variable after which outputs it.

def PairValuesWithIndexToTuples(self,val1,val2):
  t =()
  for i, (a,b) in enumerate(zip(val1,val2)):
    t += (i,a,b)
  return t

What I want to achieve is something like this if it is possible: I have been searching around but I could not find yet a solution which achieves my results from the method written above:

def PairValuesWithIndexToTuples(self,val1,val2):
  t =()
  t += for i, (a,b) in enumerate(zip(val1,val2))
  return t

or

return t+= for i, (a,b) in enumerate(zip(val1,val2))

You can make a generator expression to create the tuples, then chain.from_iterable from that expression to get the flattened result

from itertools import chain

tuple(chain.from_iterable((i, a, b) for i, (a,b) in enumerate(zip(val1,val2))))

This looks much nicer as a multiline function

def pair_with_index(*its):
    e = enumerate(zip(*its))
    flattened = ((i, *t) for i, t in e)
    c = chain.from_iterable(flattened)
    return tuple(c)

pair_with_index([1, 2, 3], [4, 5, 6])
# (0, 1, 4, 1, 2, 5, 2, 3, 6)

Edit:

My original code (for a tuple of tuples) was

def pair_with_index(val1, val2):
    return tuple((i, a, b) for i, (a,b) in enumerate(zip(val1,val2)))

pair_with_index([1, 2, 3], [4, 5, 6])
# ((0, 1, 4), (1, 2, 5), (2, 3, 6))

Perhaps you're looking for a flattened list or a flattened tuple? Not clear from your question, so I'll just include everything.

In [79]: val1 = [1,2,3]

In [80]: val2=[4,5,6]

In [81]: [(i, a, b) for i, (a,b) in enumerate(zip(val1,val2))]
Out[81]: [(0, 1, 4), (1, 2, 5), (2, 3, 6)]

In [82]: [k for j in [(i, a, b) for i, (a,b) in enumerate(zip(val1,val2))] for k in j]
Out[82]: [0, 1, 4, 1, 2, 5, 2, 3, 6]

In [84]: tuple(k for j in [(i, a, b) for i, (a,b) in enumerate(zip(val1,val2))] for k in j)
Out[84]: (0, 1, 4, 1, 2, 5, 2, 3, 6)

Because this is so much clearer...

sum(((i, a, b) for i, (a,b) in enumerate(zip(val1, val2))), ())

example:

val1 = 'hello'

val2 = range(5)

sum(((i, a, b) for i, (a,b) in enumerate(zip(val1, val2))), ())
# -> (0, 'h', 0, 1, 'e', 1, 2, 'l', 2, 3, 'l', 3, 4, 'o', 4)

While I don't advocate abusing sum , it is possible to do this in order to concatenate tuples together

sum(tuples, ())

Or in your case

sum(((i, a, b) for i, (a, b) in enumerate(zip(val1, val2))), ())

It is important to note that this can be inefficient, given the behaviors of sum. And it is not quite as clear in this instance.

Note : I do not advocate using this in production code. It is merely to show that it is possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM