Is there str.join () for lists?

I understand str.join() :

 >>> '|'.join(['1','2','3']) '1|2|3' 

Is there something that lists out? Is there a function that will output:

 ['1', '|', '2','|', '3'] 

That is, str.join() for lists? (or any other repeatable?)

+4
source share
4 answers
 list('|'.join(['1','2','3'])) 

should do the trick in which you work with a list of characters.

A more general solution that works for all objects:

 from itertools import izip_longest, chain def intersperse(myiter, value): return list( chain.from_iterable(izip_longest(myiter, [], fillvalue=value)) )[:-1] 

I am not aware of the built-in / standard library of this function.

In action:

 print intersperse([1,2,3], '|') 

outputs:

 [1, '|', 2, '|', 3] 
+5
source

How about this?

 >>> list('|'.join(['1','2','3'])) ['1', '|', '2', '|', '3'] 
+2
source
 a = [1, 2, 'str', 'foo'] print [x for y in a for x in y, '|'][:-1] # [1, '|', 2, '|', 'str', '|', 'foo'] 

In general, consider a roundrobin recipe for itertools

+1
source

This simple generator avoids creating a list (faster, saves memory):

 def intersperse(iterable, element): iterable = iter(iterable) yield next(iterable) while True: next_from_iterable = next(iterable) yield element yield next_from_iterable 

Example:

 >>> list(intersperse(['1', '2', '3'], '|')) ['1', '|', '2', '|', '3'] 
0
source

Source: https://habr.com/ru/post/1443888/


All Articles