Python list concatenation with strings into new list - python

Im looking for the best way to take a list of stirngs, generate a new list with each item from the previous list concatenated with a specific string.
Example sudo code
list1 = ['Item1','Item2','Item3','Item4']
string = '-example'
NewList = ['Item1-example','Item2-example','Item3-example','Item4-example']
Attempt
NewList = (string.join(list1))
#This of course makes one big string

If you want to create a list, a list comprehension is usually the thing to do.
new_list = ["{}{}".format(item, string) for item in list1]

Use string concatenation in a list comprehension:
>>> list1 = ['Item1', 'Item2', 'Item3', 'Item4']
>>> string = '-example'
>>> [x + string for x in list1]
['Item1-example', 'Item2-example', 'Item3-example', 'Item4-example']

An alternative to list comprehension is using map():
>>> map(lambda x: x+string,list1)
['Item1-example', 'Item2-example', 'Item3-example', 'Item4-example']
Note, list(map(lambda x: x+string,list1)) in Python3.

concate list item and string
>>>list= ['Item1', 'Item2', 'Item3', 'Item4']
>>>newList=[ i+'-example' for i in list]
>>>newList
['Item1-example', 'Item2-example', 'Item3-example', 'Item4-example']

Related

Easier way to check if an item from one list of tuples doesn't exist in another list of tuples in python

I have two lists of tuples, say,
list1 = [('item1',),('item2',),('item3',), ('item4',)] # Contains just one item per tuple
list2 = [('item1', 'd',),('item2', 'a',),('item3', 'f',)] # Contains multiple items per tuple
Expected output: 'item4' # Item that doesn't exist in list2
As shown in above example I want to check which item in tuples in list 1 does not exist in first index of tuples in list 2. What is the easiest way to do this without running two for loops?
Assuming your tuple structure is exactly as shown above, this would work:
tuple(set(x[0] for x in list1) - set(x[0] for x in list2))
or per #don't talk just code, better as set comprehensions:
tuple({x[0] for x in list1} - {x[0] for x in list2})
result:
('item4',)
This gives you {'item4'}:
next(zip(*list1)) - dict(list2).keys()
The next(zip(*list1)) gives you the tuple ('item1', 'item2', 'item3', 'item4').
The dict(list2).keys() gives you dict_keys(['item1', 'item2', 'item3']), which happily offers you set operations like that set difference.
Try it online!
This is the only way I can think of doing it, not sure if it helps though. I removed the commas in the items in list1 because I don't see why they are there and it affects the code.
list1 = [('item1'),('item2'),('item3'), ('item4')] # Contains just one item per tuple
list2 = [('item1', 'd',),('item2', 'a',),('item3', 'f',)] # Contains multiple items per tuple
not_in_tuple = []
OutputTuple = [(a) for a, b in list2]
for i in list1:
if i in OutputTuple:
pass
else:
not_in_tuple.append(i)
for i in not_in_tuple:
print(i)
You don't really have a choice but to loop over the two lists. Once efficient way could be to first construct a set of the first elements of list2:
items = {e[0] for e in list2}
list3 = list(filter(lambda x:x[0] not in items, list1))
Output:
>>> list3
[('item4',)]
Try set.difference:
>>> set(next(zip(*list1))).difference(dict(list2))
{'item4'}
>>>
Or even better:
>>> set(list1) ^ {x[:1] for x in list2}
{('item4',)}
>>>
that is a difference operation for sets:
set1 = set(j[0] for j in list1)
set2 = set(j[0] for j in list2)
result = set1.difference(set2)
output:
{'item4'}
for i in list1:
a=i[0]
for j in list2:
b=j[0]
if a==b:
break
else:
print(a)

How to reverse list of string inside nested lists in python?

I have a set of strings and a nested list of strings nested inside the list.
list1 = ['abc','def',[['abc','def']],['abc','def']].
and I want to get output similar shown below:
[['fed','cba'], [['fed','cba']], 'fed', 'cba']
when i used traditional method using built-in reverse() method and [::-1] as well. as shown below:
list1 = ['abc', 'def', [['abc', 'def']], ['abc', 'def']]
[x[::-1] for x in list1][::-1]
# and got output as [['def', 'abc'], [['abc', 'def']], 'fed', 'cba']
provide me some explanations on this?
Your problem is that you need to reverse the main list, every sublist in this list, and every string you meet on the way. You'd need some more general approach, using a recursion probably:
def deep_reverse(x):
if isinstance(x, list):
x = [deep_reverse(subx) for subx in x] # reverse every element
x = x[::-1] # reverse the list itself
elif isinstance(x, str):
x = x[::-1]
return x
list1 = ['abc','def',[['abc','def']],['abc','def']]
reversed_list1 = deep_reverse(list1)
# [['fed', 'cba'], [['fed', 'cba']], 'fed', 'cba']
Somewhat entertaining solution is to turn to string the whole list, reverse it then evaluating it.
list1 = ['abc','def',[['abc','def']],['abc','def']]
str1 = str(list1)[::-1]
str1 = str1.replace('[', '[^[') # temporary
str1 = str1.replace(']', '[')
str1 = str1.replace('[^[', ']')
list2 = eval(str1)
Though you might want to be careful of edge cases where there are strings including [ or ].

Replace the first character of every element with “$” and add “_” at the end of every element present in the list

I was able to do it by looping accessing list[i][j]. but wanted to do it without looping.
Any ideas how to do it
Example list :
Input: ["abc","def","ghi"]
Output: ["$bc_","$ef_","$hi_"]
Use a list comprehension and concatenate or format the strings you want.
inlist = ['abc','def','ghi']
outlist = [f'${s[1:]}_' for s in inlist]
You can use list comprehension:
lstIn = ['abc', 'def', 'ghi']
lstOut = [f'${i[1:]}_' for i in lstIn]
print(lstOut)
Prints:
['$bc_', '$ef_', '$hi_']
Try this
lst = ["abc","def","ghi"]
out = [ "".join(("$",s[1:],"_")) for s in lst ]
Output: print(out)
['$bc_', '$ef_', '$hi_']

splitting a list in a better way using list comprehension

I have a simple list that I am splitting and concatenating. My code uses for loop and if condition and ugly. Can you suggest a better way using list comprehension?
My code
mylist = ['10.10.10.1','10.10.10.2,10.10.10.3,10.10.10.4,10.10.10.5','10.10.10.6']
mylist = [i.split(",") for i in mylist]
list =[]
for x,y in enumerate(mylist):
if len(y) == 1:
list.append(y[0])
else:
for z in y:
list.append(z)
print(list)
I am getting the below result and exactly the way i want
['10.10.10.1','10.10.10.2','10.10.10.3','10.10.10.4','10.10.10.5','10.10.10.6']
You want:
[s for string in mylist for s in string.split(',')]
Note, your original approach wouldn't be so bad if you just simplified. No need for enumerate and no need to check the length, so just:
final_list =[]
for sub in mylist:
for s in sub:
final_list.append(s)
By the way, you shouldn't shadow the built-in list. Use another name
I agree with #juanpa.arrivillaga. However hope we can avoid that second looping since he is checking for empty values returning while splitting
In [7]: s=['10.10.10.1','','10.10.10.2,10.10.10.3,10.10.10.4,10.10.10.5','10.10.10.6']
In [8]: [splitRec for rec in s for splitRec in rec.split(',') if splitRec]
Out[8]:
['10.10.10.1',
'10.10.10.2',
'10.10.10.3',
'10.10.10.4',
'10.10.10.5',
'10.10.10.6']
In [9]: s=['10.10.10.1',',,','10.10.10.2,10.10.10.3,10.10.10.4,10.10.10.5','10.10.10.6']
In [10]: [splitRec for rec in s for splitRec in rec.split(',') if splitRec]Out[10]:
['10.10.10.1',
'10.10.10.2',
'10.10.10.3',
'10.10.10.4',
'10.10.10.5',
'10.10.10.6']
Not a comprehension, but good anyway, I think.
','.join(mylist).split(',')
You can first just split each string on ',':
>>> mylist = ['10.10.10.1','10.10.10.2,10.10.10.3,10.10.10.4,10.10.10.5','10.10.10.6']
>>> split_str = [x.split(',') for x in mylist]
>>> split_str
[['10.10.10.1'], ['10.10.10.2', '10.10.10.3', '10.10.10.4', '10.10.10.5'], ['10.10.10.6']]
Then if you want to flatten it, you can use itertools.chain.from_iterable:
>>> from itertools import chain
>>> list(chain.from_iterable(split_str))
['10.10.10.1', '10.10.10.2', '10.10.10.3', '10.10.10.4', '10.10.10.5', '10.10.10.6']

Slicing a Python list based on ending with one of a set of substrings

I have a python list
list1 = ['TC_TEST1', 'TC_TEST1_TEST2', 'TC_TEST3', 'TC_TEST1TEST2']
sublist1 = ['TEST1', 'TEST3']
Desired output is
result = ['TC_TEST1', 'TC_TEST3']
It should not contain patterns in sublist1 that occur in middle or other places in the string.
I tried using
result = [s for s in list1 if any(xs in s for xs in sublist1)]
but this also prints the patterns wherever it occurs in the string, not only the ending part.
You can try this:
list1 = {'TC_TEST1', 'TC_TEST1_TEST2', 'TC_TEST3', 'TC_TEST1TEST2'}
sublist1 = { 'TEST1', 'TEST3'}
final_list = [i for i in list1 if any(i.endswith(b) for b in sublist1)]
Output:
set(['TC_TEST3', 'TC_TEST1'])
Advanced feature with tuples:
sublist1 = ('TEST1', 'TEST3')
final_list = [i for i in list1 if i.endswith(sublist1)]
First, you need to notice that you haven't defined python lists, but sets. These are the equivalent lists derived from your defined sets (notice the []notation):
list1 = ['TC_TEST1TEST2', 'TC_TEST3', 'TC_TEST1', 'TC_TEST1_TEST2']
sublist1 = ['TEST1', 'TEST3']
If you need to filter the strings that only ends with a list of possible substrings, you can call the endswith method of a Python string passing a tuple of strings as an argument. That way, your desired output can be derived using the following expression:
result = [s for s in list1 if s.endswith(tuple(sublist1))]
Actual output is:
>>> result
['TC_TEST3', 'TC_TEST1']
Instead of using in use endswith() function so just replace result = [s for s in list1 if any(xs in s for xs in sublist1)]
with result = [s for s in list1 if any(s.endswith(xs) for xs in sublist1)],.

Categories