7

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..

5 Answers 5

5

You can try:

y = str(i) + str(x)

It should work.

Sign up to request clarification or add additional context in comments.

Comments

4

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))

1 Comment

maybe is better to use str(n) for integer value before concatenation.
1

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

Comments

1

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

1 Comment

Simple and to the point. Note that you don't really need to use f-strings here; [(item[0]+item[1].split('.')[1], item[2]) for item in list_1] should also work.
0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.