Zip Lists in Python

Zip lists in Python

When you zip() together three lists containing 20 elements each, the result has twenty elements. Each element is a three-tuple.

See for yourself:

In [1]: a = b = c = range(20)

In [2]: zip(a, b, c)
Out[2]:
[(0, 0, 0),
(1, 1, 1),
...
(17, 17, 17),
(18, 18, 18),
(19, 19, 19)]

To find out how many elements each tuple contains, you could examine the length of the first element:

In [3]: result = zip(a, b, c)

In [4]: len(result[0])
Out[4]: 3

Of course, this won't work if the lists were empty to start with.

zip function in python for lists

The issue is that zip is not used to achieve merging your lists

Here is the correct implementation

list1 = []
list2 = [0]
result=list1+list2
print(result)

# result output: [0]

However, zip function is used as an iterator between lists. below is an example to help you with the concept

a = ("1", "2", "3")
b = ("A", "B", "C")

x = zip(a, b)

for i in x: # will loop through the items in x
print(i)

# result output:
# ('1', 'A')
# ('2', 'B')
# ('3', 'C')

Python Zip list to Dataframe

If you are trying to create a dataframe from the extracted values then, you need to store them in list before performing zip

from bs4 import BeautifulSoup
import requests
import pandas as pd
import re

html_link = 'https://www.pds.com.ph/index.html%3Fpage_id=3261.html'
html = requests.get(html_link).text
soup = BeautifulSoup(html, 'html.parser')

search = re.compile(r"March.+2021")

titles = [] # to store extracted values in list
links = []
dates = []
for td in soup.find_all('td', text=search):
link = td.parent.select_one("td > a")

if link:
titles.append(link.text)
links.append(f"Link : 'https://www.pds.com.ph/{link['href']}")
dates.append(td.text)

dataframe = pd.DataFrame(zip(titles, links, dates), columns=['Titles', 'Links', 'Dates'])
# or you can use
# dataframe = pd.DataFrame({'Titles': titles, 'Links': links, 'Dates': dates})


print(dataframe)

# Titles Links Dates
# 0 RCBC Lists PHP 17.87257 Billion ASEAN Sustaina... Link : 'https://www.pds.com.ph/index.html%3Fp=... March 31, 2021
# 1 Aboitiz Power Corporation Raises 8 Billion Fix... Link : 'https://www.pds.com.ph/index.html%3Fp=... March 16, 2021
# 2 Century Properties Group, Inc Returns to PDEx ... Link : 'https://www.pds.com.ph/index.html%3Fp=... March 1, 2021
# 3 PDS Group Celebrates 2020’s Top Performers in ... Link : 'https://www.pds.com.ph/index.html%3Fp=... March 29, 2021

How to combine the elements of two lists using zip function in python?

I believe the function you are looking for is itertools.product:

lasts = ['x', 'y', 'z']
firsts = ['a', 'b', 'c']

from itertools import product
for last, first in product(lasts, firsts):
print (last, first)

x a
x b
x c
y a
y b
y c
z a
z b
z c

Another alternative, that also produces an iterator is to use a nested comprehension:

iPairs=( (l,f) for l in lasts for f in firsts)
for last, first in iPairs:
print (last, first)

Get a tuple from lists with zip() in Python

Don't put [] around the variables. Now you're zipping those lists, not the contents of the variables.

Just use:

answer = tuple(zip(name, place, weather))

How to zip 3 lists into one dictionary in python?

Do this:

soc_gp_db = {k: (v1, v2) for k, v1, v2 in zip(soc_db1, gain_db1, phase_db1)}

You need some way to express how the values get joined into a 2-tuple, you can't expect dict to make an assumption for you. Hence the explicit k: (v1, v2).

Sorting two lists together in using python zip function

Use key function lambda k: (-k[0], k[1])):

list1 = [3, 4, 2, 1, 6, 1, 4, 9, 3, 5, 8]
list2 = ['zombie', 'agatha', 'young', 'old', 'later', 'world', 'corona', 'nation', 'domain', 'issue', 'happy']
srt = sorted(zip(list1, list2), key=lambda k: (-k[0], k[1]))
print(srt)

Prints:

[(9, 'nation'), (8, 'happy'), (6, 'later'), (5, 'issue'), (4, 'agatha'), (4, 'corona'), (3, 'domain'), (3, 'zombie'), (2, 'young'), (1, 'old'), (1, 'world')]

How to zip lists of different sizes?

It's not pretty, but this is what I came up with:

In [10]: a = [1, 3, 5, 7, 9, 11]
...: b = [2, 4, 6, 8]

In [11]: output = (tuple(l[i] for l in (a,b) if i < len(l)) for i, e in enumerate(max(a,b, key=len)))

In [12]: list(output)
Out[12]: [(1, 2), (3, 4), (5, 6), (7, 8), (9,), (11,)]

Make it a function:

from collections.abc import (Iterable, Iterator)
from itertools import count

def zip_staggered(*args: Iterable) -> Iterator[tuple]:
for i in count():
if (next_elem := tuple(a[i] for a in args if i < len(a))):
yield next_elem
else:
break


Related Topics



Leave a reply



Submit