Reputation: 75
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..
Upvotes: 5
Views: 5361
Reputation: 411
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]
Upvotes: 0
Reputation: 11
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
Upvotes: 1
Reputation: 7222
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
Upvotes: 1
Reputation: 477824
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))
Upvotes: 4