How to replace list element with string without double quotes? - python-3.x

I have a simple list like this:
list = ['A','B','C']
and to replace element #1 of l1 with this string:
str = "'W','T'"
I'm doing like this:
>>> list[1] = str
>>> list
['A', "'W','T'", 'C']
How can I do to replace list[1] values with str content without the double quotes? like this:
['A','W','T','C']

You can't insert it directly like that. You need to clean it first and convert it to a list and use slicing.
list1 = ['A','B','C']
str1 = "'W','T'"
new_list = [a.strip("'") for a in str1.split(",")]
list1 = list1[:1] + new_list + list1[2:]
print(list1) # ['A', 'W', 'T', 'C']
I also modified your variable names because list and str are reserved keywords.

You have to put the elements of the string into a list and then add the list elements to the desired position in your destination list.
list_ = ['A', 'B', 'C']
string = "'W','T'"
formatted = [letter for letter in string if letter.isalpha()]
i = 1 #index of element to replace
list_[i:(i + len(formatted))-1] = formatted
print(list_)

list[item] = str(list[item])
>>> mylist = [1,3,5]
>>> mylist[0] = str(mylist[0])
>>> mylist
['1', 3, 5]
>>>

Related

How to make a nested list in python

Suppose I have a 2 lists in my python script:
my_list = ['hat', 'bat']
other_list = ['A', 'B', 'C']
I want to iterate through other_list and create a nested list for 'bat's that adds '_' + other_list item to a the 'bat' and puts it in a nested list:
for item in other_list:
for thing in my_list:
if thing == 'bat':
print(thing + '_' + item)
My desired outcome would be new_list = ['hat',['bat_A', 'bat_B', 'bat_C']]
How would I achieve this?
I tried the below, but it produces this: ['hat', 'hat', 'hat', ['bat_A', 'bat_B', 'bat_C']]
new_list = []
extra = []
for item in other_list:
for thing in my_list:
if thing == 'bat':
extra.append(thing + '_' + item)
else:
new_list.append(thing)
new_list.append(extra)
Try this:
>>> my_list = ['hat', 'bat']
>>> other_list = ['A', 'B', 'C']
>>> new_list=[my_list[0], [f'{my_list[1]}_{e}' for e in other_list]]
>>> new_list
['hat', ['bat_A', 'bat_B', 'bat_C']]
If your question (which is a little unclear) is just about reacting to 'bat' with a different reaction, you can do this:
my_list = ['hat', 'bat','cat']
other_list = ['A', 'B', 'C']
new_list=[]
for e in my_list:
if e=='bat':
new_list.append([f'{e}_{x}' for x in other_list])
else:
new_list.append(e)
>>> new_list
['hat', ['bat_A', 'bat_B', 'bat_C'], 'cat']
Which can be reduced to:
>>> [[f'{e}_{x}' for x in other_list] if e=='bat' else e for e in my_list]
['hat', ['bat_A', 'bat_B', 'bat_C'], 'cat']
I think will work
my_list = ['hat', 'bat']
other = ['A', 'B' , 'C']
new_list = []
extra = []
for item in my_list:
if item == 'bat':
for char in other:
extra.append(item + '_' + char)
else:
new_list.append(item)
new_list.append(extra)
print(new_list)
OK, this is just my answer, but it seems to work. I think is clunky though, and I'm hoping for a better answer
my_list = ['hat', 'bat']
other_list = ['A', 'B', 'C']
new_list = []
extra = []
for item in other_list:
for thing in my_list:
if thing == 'bat':
extra.append(thing + '_' + item)
else:
if thing not in new_list:
new_list.append(thing)
new_list.append(extra)

Python: Convert 2d list to dictionary with indexes as values

I have a 2d list with arbitrary strings like this:
lst = [['a', 'xyz' , 'tps'], ['rtr' , 'xyz']]
I want to create a dictionary out of this:
{'a': 0, 'xyz': 1, 'tps': 2, 'rtr': 3}
How do I do this? This answer answers for 1D list for non-repeated values, but, I have a 2d list and values can repeat. Is there a generic way of doing this?
Maybe you could use two for-loops:
lst = [['a', 'xyz' , 'tps'], ['rtr' , 'xyz']]
d = {}
overall_idx = 0
for sub_lst in lst:
for word in sub_lst:
if word not in d:
d[word] = overall_idx
# Increment overall_idx below if you want to only increment if word is not previously seen
# overall_idx += 1
overall_idx += 1
print(d)
Output:
{'a': 0, 'xyz': 1, 'tps': 2, 'rtr': 3}
You could first convert the list of lists to a list using a 'double' list comprehension.
Next, get rid of all the duplicates using a dictionary comprehension, we could use set for that but would lose the order.
Finally use another dictionary comprehension to get the desired result.
lst = [['a', 'xyz' , 'tps'], ['rtr' , 'xyz']]
# flatten list of lists to a list
flat_list = [item for sublist in lst for item in sublist]
# remove duplicates
ordered_set = {x:0 for x in flat_list}.keys()
# create required output
the_dictionary = {v:i for i, v in enumerate(ordered_set)}
print(the_dictionary)
""" OUTPUT
{'a': 0, 'xyz': 1, 'tps': 2, 'rtr': 3}
"""
also, with collections and itertools:
import itertools
from collections import OrderedDict
lstdict={}
lst = [['a', 'xyz' , 'tps'], ['rtr' , 'xyz']]
lstkeys = list(OrderedDict(zip(itertools.chain(*lst), itertools.repeat(None))))
lstdict = {lstkeys[i]: i for i in range(0, len(lstkeys))}
lstdict
output:
{'a': 0, 'xyz': 1, 'tps': 2, 'rtr': 3}

Why does not ''.join(list1) work after insert a new element?

I have a list list = ['a', 'b']. Then I create a new list by list1 = list.insert(0, 'c'). After that I want to join all the strings in list1 by ''.join(list1). Could you please explain why how to resolve the error can only join an iterable?
list = ['a', 'b']
list1 = list.insert(0, 'c')
''.join(list1)
list.insert(0, 'c') does not return anything, so to do this you can write
list = ['a', 'b']
list.insert(0, 'c')
print(''.join(list))
Output: 'cab'

Convert a string within a list to an element in the list in python

I am using python data to create a ReportLab report. I have a list that looks like this:
mylist = [['a b c d e f'],['g h i j k l']]
and want to convert it to look like this:
mylist2 = [[a,b,c,d,e],[g,h,i,j,k,l]]
the first list gives me a "List out of index" error when building the report.
the second list works in ReportLab, but columns and formatting in this list aren't what I want.
What is the best method to convert mylist 1 to mylist2 in python?
string to list can be done using split() method.
try mylist[1][0].split() and mylist[0][0].split()
Borrowing idea from Jibin Mathews, I tried the following
new_list = [mylist[0][0].split(), mylist[1][0].split()]
and it prints
[['a', 'b', 'c', 'd', 'e', 'f'], ['g', 'h', 'i', 'j', 'k', 'l']]
I saw 'f' is missing in your final list. Is that the mistake?
mylist = [['a b c d e f'],['g h i j k l']]
import re
space_re = re.compile(r'\s+')
output = []
for l in mylist:
element = l[0]
le = re.split(space_re, element)
output.append(le)
This not best answer but it will work fine.!

Inserting list into another list using loops only:

I'm using the current version of python. I need to return a copy of list1 with list2 inserted at the position indicated by index i.e if the index value is 2, list2 is inserted into list 1 at position 2. I can only use for/while loops, the range function & the list_name.append (value) methods and the lists cannot be sliced. So if list1 list1 = boom list2 = red and the index value = 2, how do I return a new list = boredom? I have this so far:
list1 = ['b','o','o','m']
list2 = ['r','e','d']
index = 2
new_list = []
if index > len(list1):
new_list = list1 + list2
print (new_list)
if index <= 0:
new_list = list2 + list1
print (new_list)
An alternative approach to Padriac's - using three for loops:
list1 = ['b','o','o','m']
list2 = ['r','e','d']
n = 2
new_list = []
for i in range(n): # append list1 until insert point
new_list.append(list1[i])
for i in list2: # append all of list2
new_list.append(i)
for i in range(n, len(list1)): # append the remainder of list1
new_list.append(list1[i])
Once you hit the index, use an inner loop to append each element from list2:
for ind, ele in enumerate(list1):
# we are at the index'th element in list1 so start adding all
# elements from list2
if ind == index:
for ele2 in list2:
new_list.append(ele2)
# make sure to always append list1 elements too
new_list.append(ele)
print(new_list)
['b', 'o', 'r', 'e', 'd', 'o', 'm']
If you must use range just replace enumerate with range:
new_list = []
for ind in range(len(list1)):
if ind == index:
for ele2 in list2:
new_list.append(ele2)
new_list.append(list1[ind])
print(new_list)
['b', 'o', 'r', 'e', 'd', 'o', 'm']
Or without ifs using extend and remove if allowed:
new_list = []
for i in range(index):
new_list.append(list1[i])
list1.remove(list1[i])
new_list.extend(list2)
new_list.extend(list1)
Appending as soon as we hit the index means the elements will be inserted from the correct index, the elements from list1 must always be appended after your if check.
Check out this small snippet of code I've written.
Check the while condition that is used. I hope it will answer your question.
email = ("rishavmani.bhurtel#gmail.com")
email_split = list(email)
email_len = len(email)
email_uname_len = email_len - 10
email_uname = []
a = 0
while (a < email_uname_len):
email_uname[a:email_uname_len] = email_split[a:email_uname_len]
a = a + 1
uname = ''.join(email_uname)
uname = uname.replace(".", " ")
print("Possible User's Name can be = %s " %(uname))

Resources