Ad
Python: List Comprehension To Access Multiple Lists
list1 = []
list.append([item1[i], item2[i], item3[i] for i in range(2)])
i.e how to populate list1 with [[item1[0], item2[0], item3[0]],[item1[1], item2[1], item3[1]]]
through list comprehension where item1, item2 item3 are different lists?
Example:
item1 = [1,2,3,4]
item2 = [1,4,9,16]
item3 = [1,8,27,64]
# I want list1 =
[[1,1,1],
[2,4,8],
[3,9,27],
[4,16,64]]
# through list comprehension AND APPEND STATEMENT
Ad
Answer
Add another set of []
's to your code:
list1 = []
list1.append([[item1[i], item2[i], item3[i]] for i in range(len(item1))])
Note that this assumes that item1
, item2
and item3
are all the same length
Alternately, for an exact match of your expected output, use the following:
list1 = [[item1[i], item2[i], item3[i]] for i in range(len(item1))]
Example data and output
item1 = [1, 2, 3]
item2 = ["A", "B", "C"]
item3 = [0.1, 0.2, 0.3]
list1 = [[item1[i], item2[i], item3[i]] for i in range(len(item1))]
print(list1)
>>> [[1, 'A', 0.1], [2, 'B', 0.2], [3, 'C', 0.3]]
Using .append()
, the list comprehension becomes:
for i in range(len(item1)):
list1.append([item1[i], item2[i], item3[i]])
However, if you want to use a list comprehension and still append the newly created lists onto list1
, use +=
rather than .append()
:
list1 += [[item1[i], item2[i], item3[i]] for i in range(len(item1))]
.append()
adds the given item onto the end of the list. +=
will instead add each sublist individually.
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad