I have a list1 like this,
list1 = [('my', '1.2.3', 2),('name', '9.8.7', 3)]
I want to get a new list2 like this (joining first element with second element's second entry);
list2 = [('my2', 2),('name8', 3)]
As a first step, I am checking to join the first two elements in the tuple as follow,
for i,j,k in list1:
#print(i,j,k)
x = j.split('.')[1]
y = str(i).join(x)
print(y)
but I get this
2
8
I was expecting this;
my2
name8
what I am doing wrong? Is there any good way to do this? a simple way..
try
y = str(i) + str(x)
it should works.
The str(i).join(x), means that you see x as an iterable of strings (a string is an iterable of strings), and you are going to construct a string by adding i in between the elements of x.
You probably want to print('{}{}'.format(i+x)) however:
for i,j,k in list1:
x = j.split('.')[1]
print('{}{}'.format(i+x))
Try this:
for x in list1:
print(x[0] + x[1][2])
or
for x in list1:
print(x[0] + x[1].split('.')[1])
output
# my2
# name8
You should be able to achieve this via f strings and list comprehension, though it'll be pretty rigid.
list_1 = [('my', '1.2.3', 2),('name', '9.8.7', 3)]
# for item in list_1
# create tuple of (item[0], item[1].split('.')[1], item[2])
# append to a new list
list_2 = [(f"{item[0]}{item[1].split('.')[1]}", f"{item[2]}") for item in list_1]
print(list_2)
List comprehensions (and dict comprehensions) are some of my favorite things about python3
https://www.pythonforbeginners.com/basics/list-comprehensions-in-python
https://www.digitalocean.com/community/tutorials/understanding-list-comprehensions-in-python-3
Going with the author's theme,
list1 = [('my', '1.2.3', 2),('name', '9.8.7', 3)]
for i,j,k in list1:
extracted = j.split(".")
y = i+extracted[1] # specified the index here instead
print(y)
my2
name8
[Program finished]
How do you turn a list that contain pairs into a list that contains tuple pairs by using easy programming e.g for loop? x,y = ...?
My code:
def read_numbers():
numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
numbers.split(',')
x,y = tuple numbers
return numbers
desire output:
[(68,125), (113,69), (65,86), (108,149), (152,53), (78,90)]
def read_numbers():
numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
return [tuple(map(int,pair.split(','))) for pair in numbers]
Try this by using nested list comprehension:
o = [tuple(int(y) for y in x.split(',')) for x in numbers]
Just use list comprehension. Read more about it here!
# Pass in numbers as an argument so that it will work
# for more than 1 list.
def read_numbers(numbers):
return [tuple(int(y) for y in x.split(",")) for x in numbers]
Here is a breakdown and explanation (in comments) of the list comprehension:
[
tuple( # Convert whatever is between these parentheses into a tuple
int(y) # Make y an integer
for y in # Where y is each element in
x.split(",") # x.split(","). Where x is a string and x.split(",") is a list
# where the string is split into a list delimited by a comma.
) for x in numbers # x is each element in numbers
]
However, if you are just doing it for one list, there is no need to create a function.
Try this :
def read_numbers():
numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
final_list = []
[final_list.append(tuple(int(test_str) for test_str in number.split(','))) for number in numbers]
return final_list
I have three lists and want to sort and generate two new list. Can any one please tell how it can be done?
list1=[12,25,45], list2=[14,69], list3=[54,98,68,78,48]
I want to print the output like
chosen1=[12,14,54], rest1=[25,45,69,98,68,78,48]
chosen2=[12,14,98], rest2=[25,45,69,54,68,78,48]
and so on
(every possible combination for chosen list)
I have tried to write this but I don't know
list1=[12,25,45]
list2=[14,69]
list3=[54,98,68,78,48]
for i in xrange (list1[0],list1[2]):
for y in xrange(list2[0], list2[1]):
for z in xrange(list[0],list[4])
for a in xrange(chosen[0],[2])
chosed1.append()
for a in xrange(chosen[0],[7])
rest1.append()
Print rest1
Print chosen1
itertools.product generates all permutations of selecting one thing each out of different sets of things:
import itertools
list1 = [12,25,45]
list2 = [14,69]
list3 = [54,98,68,78,48]
for i,(a,b,c) in enumerate(itertools.product(list1,list2,list3),1):
# Note: Computing rest this way will *not* work if there are duplicates
# in any of the lists.
rest1 = [n for n in list1 if n != a]
rest2 = [n for n in list2 if n != b]
rest3 = [n for n in list3 if n != c]
rest = ','.join(str(n) for n in rest1+rest2+rest3)
print('chosen{0}=[{1},{2},{3}], rest{0}=[{4}]'.format(i,a,b,c,rest))
Output:
chosen1=[12,14,54], rest1=[25,45,69,98,68,78,48]
chosen2=[12,14,98], rest2=[25,45,69,54,68,78,48]
chosen3=[12,14,68], rest3=[25,45,69,54,98,78,48]
chosen4=[12,14,78], rest4=[25,45,69,54,98,68,48]
chosen5=[12,14,48], rest5=[25,45,69,54,98,68,78]
chosen6=[12,69,54], rest6=[25,45,14,98,68,78,48]
chosen7=[12,69,98], rest7=[25,45,14,54,68,78,48]
chosen8=[12,69,68], rest8=[25,45,14,54,98,78,48]
chosen9=[12,69,78], rest9=[25,45,14,54,98,68,48]
chosen10=[12,69,48], rest10=[25,45,14,54,98,68,78]
chosen11=[25,14,54], rest11=[12,45,69,98,68,78,48]
chosen12=[25,14,98], rest12=[12,45,69,54,68,78,48]
chosen13=[25,14,68], rest13=[12,45,69,54,98,78,48]
chosen14=[25,14,78], rest14=[12,45,69,54,98,68,48]
chosen15=[25,14,48], rest15=[12,45,69,54,98,68,78]
chosen16=[25,69,54], rest16=[12,45,14,98,68,78,48]
chosen17=[25,69,98], rest17=[12,45,14,54,68,78,48]
chosen18=[25,69,68], rest18=[12,45,14,54,98,78,48]
chosen19=[25,69,78], rest19=[12,45,14,54,98,68,48]
chosen20=[25,69,48], rest20=[12,45,14,54,98,68,78]
chosen21=[45,14,54], rest21=[12,25,69,98,68,78,48]
chosen22=[45,14,98], rest22=[12,25,69,54,68,78,48]
chosen23=[45,14,68], rest23=[12,25,69,54,98,78,48]
chosen24=[45,14,78], rest24=[12,25,69,54,98,68,48]
chosen25=[45,14,48], rest25=[12,25,69,54,98,68,78]
chosen26=[45,69,54], rest26=[12,25,14,98,68,78,48]
chosen27=[45,69,98], rest27=[12,25,14,54,68,78,48]
chosen28=[45,69,68], rest28=[12,25,14,54,98,78,48]
chosen29=[45,69,78], rest29=[12,25,14,54,98,68,48]
chosen30=[45,69,48], rest30=[12,25,14,54,98,68,78]
If you need to get 2 digit combinations from the two list and the remaining then this would be the solution:
import itertools
list1 = [12,25,45]
list2 = [14,69]
list3 = [21,34,56,32]
chosen = []
leftover = []
mergedlist = list(set(list1 + list2 + list3))
mergedNewList = [x for x in itertools.permutations(mergedlist,3)]
for i,value in enumerate(mergedNewList):
chosen.append(list(value))
leftover.append([j for j in mergedlist if j not in chosen[i]])
print chosen[i]
print leftover[i]`
I have appended the values in a single variable for chosen and for the rest in leftover as this is the most pythonic way of storing the values.
Can anyone tell me how can I call for indexes in a nested list?
Generally I just write:
for i in range (list)
but what if I have a list with nested lists as below:
Nlist = [[2,2,2],[3,3,3],[4,4,4]...]
and I want to go through the indexes of each one separately?
If you really need the indices you can just do what you said again for the inner list:
l = [[2,2,2],[3,3,3],[4,4,4]]
for index1 in xrange(len(l)):
for index2 in xrange(len(l[index1])):
print index1, index2, l[index1][index2]
But it is more pythonic to iterate through the list itself:
for inner_l in l:
for item in inner_l:
print item
If you really need the indices you can also use enumerate:
for index1, inner_l in enumerate(l):
for index2, item in enumerate(inner_l):
print index1, index2, item, l[index1][index2]
Try this setup:
a = [["a","b","c",],["d","e"],["f","g","h"]]
To print the 2nd element in the 1st list ("b"), use print a[0][1] - For the 2nd element in 3rd list ("g"): print a[2][1]
The first brackets reference which nested list you're accessing, the second pair references the item in that list.
You can do this. Adapt it to your situation:
for l in Nlist:
for item in l:
print item
The question title is too wide and the author's need is more specific. In my case, I needed to extract all elements from nested list like in the example below:
Example:
input -> [1,2,[3,4]]
output -> [1,2,3,4]
The code below gives me the result, but I would like to know if anyone can create a simpler answer:
def get_elements_from_nested_list(l, new_l):
if l is not None:
e = l[0]
if isinstance(e, list):
get_elements_from_nested_list(e, new_l)
else:
new_l.append(e)
if len(l) > 1:
return get_elements_from_nested_list(l[1:], new_l)
else:
return new_l
Call of the method
l = [1,2,[3,4]]
new_l = []
get_elements_from_nested_list(l, new_l)
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
results = []
for numbers in lists:
for numbers2 in numbers:
results.append(numbers2)
return results
print flatten(n)
Output: n = [1,2,3,4,5,6,7,8,9]
I think you want to access list values and their indices simultaneously and separately:
l = [[2,2,2],[3,3,3],[4,4,4],[5,5,5]]
l_len = len(l)
l_item_len = len(l[0])
for i in range(l_len):
for j in range(l_item_len):
print(f'List[{i}][{j}] : {l[i][j]}' )