Combining every 2 string to 1 string

I have a list a

list = ['247400015203223811', 'DPF', '247400015203223813', 'ZPF']


I want to get a list of strings like ["247400015203223811, DPF", "247400015203223813, ZPF"]
combining every 2 strings to 1 string

I tried like


list2 = []
list = ['247400015203223811', 'DPF', '247400015203223813', 'ZPF']

for i in range(0, len(list), 2):
list2.append(list[i] + list[i])


is this even possible?

You almost had it, you can use this list comprehension:

mylist = ['247400015203223811', 'DPF', '247400015203223813', 'ZPF']

mylist2 = [mylist[i]+', '+mylist[i+1]for i in range(0,len(mylist),2)]

>>> mylist2
['247400015203223811, DPF', '247400015203223813, ZPF']


Make sure you don't use the keyword list as a variable name, because it masks the python built-in type (I changed it to mylist instead)

Of course is possible, and you almost got the answer:
you simply have to add 1 to the index of the second word:

list2 = []

list1 = ['247400015203223811', 'DPF', '247400015203223813', 'ZPF']

for i in range(0, len(list1), 2):
list2.append(list1[i] + list1[i+1])

print(list2) # OUTPUT: ['247400015203223811DPF', '247400015203223813ZPF']


but you maybe want also to have a dot between the 2 words:

list2.append(list1[i] + '.' + list1[i+1]) # OUTPUT: ['247400015203223811.DPF', '247400015203223813.ZPF']


I think slicing and zip can work nicely here:

# assuming list of stringals is named `strings`
even_indexed = strings[::2]
odd_indexed = strings[1::2]

# create pairs to join
pairs = zip(even_indexed, odd_indexed)

# join all pairs
result = list(map(', '.join, pairs))


Can't test but this gets the idea across.

One common pattern to pair items in a list is to get an iterator over the list, then zip that iterator with itself. From there, joining the pairs with ", " is as easy as calling str.join

# Don't reuse the name list, it already has a meaning
list_ = ['247400015203223811', 'DPF', '247400015203223813', 'ZPF']

it = iter(list_)

print([", ".join(pair) for pair in zip(it, it)])
# ['247400015203223811, DPF', '247400015203223813, ZPF']


You can slice the list, zip the slices and map them to join:

l = ['247400015203223811', 'DPF', '247400015203223813', 'ZPF']
print(list(map(', '.join, zip(l[::2], l[1::2]))))


This outputs:

['247400015203223811, DPF', '247400015203223813, ZPF']


Using list comprehension

list = ['247400015203223811', 'DPF', '247400015203223813', 'ZPF']
res = [ ', '.join(x) for x in zip(list[0::2], list[1::2]) ]


output:

['247400015203223811, DPF', '247400015203223813, ZPF']


Let's give you the one-line style solution, easily readable:

list_ = ['247400015203223811', 'DPF', '247400015203223813', 'ZPF']
print([", ".join(i) for i in zip(list_[0::2], list_[1::2])])
# ['247400015203223811, DPF', '247400015203223813, ZPF']


Note that:


list_[0::2] is the list of elements of list_ with even index
list_[1::2] is the list of elements of list_ with odd index


zip the Iterator over the list together with itself in order to get pairs of two.

Demo of the principle:

>>> lst = ['247400015203223811', 'DPF', '247400015203223813', 'ZPF']
>>> it = iter(lst)
>>> list(zip(it, it))
[('247400015203223811', 'DPF'), ('247400015203223813', 'ZPF')]


Applying the principle in a list comprehension:

>>> [', '.join(s) for s in zip(*[iter(lst)]*2)]
['247400015203223811, DPF', '247400015203223813, ZPF']


No extra memory for slices or intermediary lists needed. No fiddling around with indexes.

import itertools

def grouper(iterable, n, fillvalue=None):
""" Collect data into fixed-length chunks or blocks.

grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
"""
args = [iter(iterable)] * n
return itertools.zip_longest(*args, fillvalue=fillvalue)

x = ["a", "b", "c", "d", "e"]
x_grouped = [", ".join(pair) for pair in grouper(x, 2, "")]

print(x_grouped) # -> ['a, b', 'c, d', 'e, ']


You can use the grouper function from an itertools recipe. If you have an odd number of strings in your list, you can specify a fillvalue.

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

React Native - Image Cache