dimanche 25 mai 2014

python - création des tuples de 3 s - Stack Overflow


Hi please how can i make a tuple of 3s out of a 2 lists of tuples of (2s and 1s)


list1 = [(2345,7465), (3254,9579)]
list2 = [{'type': '62', 'length': 0.15, 'lanes': 1, 'modes': 'cwt'}, {'type': '62', 'length': 0.16, 'lanes': 1, 'modes': 'cwt'}]

The output should look like this:


list3 = [(2345,7465,{'type': '62', 'length': 0.15, 'lanes': 1, 'modes': 'cwt'}), (3254,9579,{'type': '62', 'length': 0.16, 'lanes': 1, 'modes': 'cwt'})]



Use zip() to pair up the lists and produce tuples from that:


list3 = [(l1[0], l1[1], l2) for l1, l2 in zip(list1, list2)]

Demo:


>>> list1 = [(2345,7465), (3254,9579)]
>>> list2 = [{'type': '62', 'length': 0.15, 'lanes': 1, 'modes': 'cwt'}, {'type': '62', 'length': 0.16, 'lanes': 1, 'modes': 'cwt'}]
>>> [(l1[0], l1[1], l2) for l1, l2 in zip(list1, list2)]
[(2345, 7465, {'lanes': 1, 'length': 0.15, 'type': '62', 'modes': 'cwt'}), (3254, 9579, {'lanes': 1, 'length': 0.16, 'type': '62', 'modes': 'cwt'})]



Based on index using list comprehension:


[ list1[i1]+(list2[i1],) for i1 in range(len(list1))]

Output:


[(2345, 7465, {'lanes': 1, 'length': 0.15, 'type': '62', 'modes': 'cwt'}), (3254, 9579, {'lanes': 1, 'length': 0.16, 'type': '62', 'modes': 'cwt'})]


Hi please how can i make a tuple of 3s out of a 2 lists of tuples of (2s and 1s)


list1 = [(2345,7465), (3254,9579)]
list2 = [{'type': '62', 'length': 0.15, 'lanes': 1, 'modes': 'cwt'}, {'type': '62', 'length': 0.16, 'lanes': 1, 'modes': 'cwt'}]

The output should look like this:


list3 = [(2345,7465,{'type': '62', 'length': 0.15, 'lanes': 1, 'modes': 'cwt'}), (3254,9579,{'type': '62', 'length': 0.16, 'lanes': 1, 'modes': 'cwt'})]


Use zip() to pair up the lists and produce tuples from that:


list3 = [(l1[0], l1[1], l2) for l1, l2 in zip(list1, list2)]

Demo:


>>> list1 = [(2345,7465), (3254,9579)]
>>> list2 = [{'type': '62', 'length': 0.15, 'lanes': 1, 'modes': 'cwt'}, {'type': '62', 'length': 0.16, 'lanes': 1, 'modes': 'cwt'}]
>>> [(l1[0], l1[1], l2) for l1, l2 in zip(list1, list2)]
[(2345, 7465, {'lanes': 1, 'length': 0.15, 'type': '62', 'modes': 'cwt'}), (3254, 9579, {'lanes': 1, 'length': 0.16, 'type': '62', 'modes': 'cwt'})]


Based on index using list comprehension:


[ list1[i1]+(list2[i1],) for i1 in range(len(list1))]

Output:


[(2345, 7465, {'lanes': 1, 'length': 0.15, 'type': '62', 'modes': 'cwt'}), (3254, 9579, {'lanes': 1, 'length': 0.16, 'type': '62', 'modes': 'cwt'})]

0 commentaires:

Enregistrer un commentaire