Im using python3 and i want to make this list to containe only the temp items and removing all the spaces and singel quotes.
a = ["', ' 'temp1', ' 'temp12', ' 'temp3', ' 'temp4', ' 'temp5' "]
I want it to look like this :
['temp1','temp12','temp3','temp4','temp5']
How can i do this ?
Things like this was explained here billion times, but here you are:
import re
pattern = r'(\w+\d+)'
s = "', ' 'temp1', ' 'temp12', ' 'temp3', ' 'temp4', ' 'temp5' "
result = re.findall(pattern, s)
Result:
['temp1', 'temp12', 'temp3', 'temp4', 'temp5']
One way to go about this :
result = a[0].replace(' ', '').replace("'", '')[1:].split(',')
print(result)
Output:
['temp1', 'temp12', 'temp3', 'temp4', 'temp5']
I tried splitting the list element over single quote and then traversed through all the elements of the created list (used list comprehension) : fetched only those elements which contain the word 'temp'
print ([i for i in a[0].split("'") if 'temp' in i])
Related
['key=IAfpK', ' age=58', ' key=WNVdi', ' age=64', ' key=jp9zt', ' age=47', ' key=0Sr4C', ' age=68', ' key=CGEqo', ' age=76', ' key=IxKVQ', ' age=79', ' key=eD221', ' age=29']
I got the following list, i need to convert it to a dictionary,like
{"IAfpK":58,"WNVdi":,"64":,.....}
I have tried ast library and JSON.loads but in vain
Simple one-liner using a dict comprehension:
{x.split("=")[1]: int(y.split("=")[1]) for x,y in zip(arr[::2],arr[1::2])}
zip(arr[::2],arr[1::2]) iterates over pairs of the array, and str.split extracts the correct value for the key and value.
If you know that your list is always following this exact format and order, just loop through the list:
mydict = {}
for element in mylist:
if "key=" in element:
mydict[element.replace("key=", "")] = None
else:
mydict[mydict.keys()[-1]] = int(element.replace("age=", ""))
Given you a list arr of the shape [' key=aKey', ' age=valueForAKey', ' key=bKey', ...] (note the space at the start of each list element).
You can use this dictionary comprehension to extract the matching key and values and build the resulting dictionary.
{arr[i][5:]: arr[i+1][5:] for i in range(0, len(arr), 2)}
Try it out here: https://www.online-python.com/iGI3A2YEnr
If the number of leading spaces is inconsistent (as in the example you gave), you can use the lstrip() method to remove the leading spaces.
{arr[i].lstrip()[4:]: arr[i+1].lstrip()[4:] for i in range(0, len(arr), 2)}
I have an arbitrarily nested array of values that looks like this:
['"multiply"', 'ALAssn ', ['ACmp ', ['Ge ', ['Var "n"'], ' ', ['Num 0']]], ['ALAssn ', ['ACmp ', ['Eq ', ['Var "p"'], ' ', ['Mul ', ['Var "n"'], ' ', ['Var "m"']]]]]
and I need to try and figure out a way to parse through the every value in the array and format it so that:
Each array of length 1 is split into two separate values:
-- Example: ['Var "n"'] should now become ["Var", "n"] and ['Num 0'] now becomes ["Num", 0].
All instances of empty list values are removed.
-- Example: ['Ge ', ['Var "n"'], ' ', ['Num 0']] now becomes ['Ge ', ['Var "n"'], ['Num 0']]
The whitespace in any string is removed.
-- Example: 'Ge ' now becomes 'Ge'
The given snippet is a portion of a much larger string that needs to parsed. I understand what needs to be done at a high level..ie:
Once I get to an list of length 1, list.split(" ") to split into two separate elements, then trim arr[1] to get rid of the extra quotation marks
If el is an empty string for every element in the list, list.remove(el)
Check if isinstance(el, string) of every element when traversing, and if true, el.replace(" ", "") to rid of the whitespace.
My only issue comes when traversing through every single element in the list. I've tried doing so recursively and iteratively, but so far haven't been able to crack it.
Ideally, I traverse through every single element, and then once I hit an element that meets the criteria, set that element equal to the change that I want to make on it. This is only really the case for points 1 and 3.
EDIT:
Thank you so much for the answers given. I have one more addition I would like to make.
Assume too I have a nested identifiers like 'Reads "a"' as the first value of an array, with the possibility of having addition identifiers like Write "a" in the same level. These also needs to be converted to the format ["Read", "a"]. See the change in the large list below. How would I go about doing this?
['Read "a"', ['Add', ['Var', 'i'], ['Num', '1']]], 'Write "a"', ['Add', ['Var', 'i'], ['Num', '1']], ['Var', 't']]
The point of these values 'Read' and 'Write' is so that, when traversing the list, we know the "type" of the next n elements of the list corresponding to that identifier. We can distinguish them basically by saying they are are the only values in the nested list that will not be lists themselves.
For example: ['identifier', [], [], []]
Assume it is known that the identifier type contains 3 lists, first, second, third. The goal is to read identifier and then store first, second, and third as nodes in a tree, for example.
This problem seems like it would be easiest to deal with by constructing a new list with the fixed-up items, rather than trying to modify the existing list in place. This would let you use recursion to deal with the nesting, while using iteration over the flat parts of each list.
I'd structure the code like this:
def process(lst):
if len(lst) == 1: # special case for one-element lists
result = lst[0].split()
result[1] = result[1].strip('"') # strip quotation marks
return result
result = []
for item in lst:
if isinstance(item, list):
result.append(process(item)) # recurse on nested lists
else: # item is a string
stripped = item.strip() # remove leading and trailing whitespace
if stripped:
result.append(stripped) # keep only non-empty strings
return result
Seems you can collapse 1 and 3 into one operation:
def sanitize(item):
if isinstance(item, list):
if len(item) == 1:
item = item[0].split()
return [output for i in item if (output := sanitize(i))]
return item.strip('" ') # Strips both '"' and ' '.
item = ['"multiply"', 'ALAssn ', ['ACmp ', ['Ge ', ['Var "n"'], ' ', ['Num 0']]], ['ALAssn ', ['ACmp ', ['Eq ', ['Var "p"'], ' ', ['Mul ', ['Var "n"'], ' ', ['Var "m"']]]]]]
sanitize(item)
# Returns: ['multiply', 'ALAssn', ['ACmp', ['Ge', ['Var', 'n'], ['Num', '0']]], ['ALAssn', ['ACmp', ['Eq', ['Var', 'p'], ['Mul', ['Var', 'n'], ['Var', 'm']]]]]]
For example, I have this list:
['I am the ', 'ugliest person']
I would like to make this list like:
['I-am-the ', 'ugliest-person']
You can do this:
lst = ['I am the ', 'ugliest person']
lst = ['-'.join(val.split()) for val in lst]
val.split() will split val on any whitespace, and then we rejoin all the split elements with -.
To preserve any spaces on the edge of each element of lst, you can add these functions:
def get_ending_spaces(val):
return ' ' * (len(val) - len(val.rstrip()))
def get_beginning_spaces(val):
return ' ' * (len(val) - len(val.lstrip()))
and change the list comprehension to
lst = [get_beginning_spaces(val) + '-'.join(val.split()) + get_ending_spaces(val) for val in lst]
If all your usecases are like your example (where there's no left whitespace), then feel free to remove the get_beginning_spaces call.
Output for
[' I am the ', ' ugliest person ']
ends up being
[' I-am-the ', ' ugliest-person ']
you can try the below list comprehension
new_list = [x.replace(' ','-') for x in list]
This will create a new list named 'new_list' with the spaces replaced with dashes (-)
Hope this helps
Edit: The above code does not preserve the trailing spaces as commented by OP. The below change will probably fix it (only if a single trailing space is involved :/)
new_list = [x[:-1].replace(' ','-') if x[-1]==' ' else x.replace(' ','-') for x in list]
So a proper solution will be more like this:
def replace_spaces(sentence):
l = sentence.split(' ')
l = [x if x for x in l]
return '-'.join(l)
new_list = [ replace_spaces(x) for x in list]
You can use re to do this:
import re
l = ['I am the ', 'ugliest person']
for i,s in enumerate(l):
for n in re.findall('\w *?\w',s): # Finds all spaces that are between 2 letters
s = s.replace(n,n.replace(' ','-')) # Only replace the spaces that are between 2 letters
l[i] = s
print(l)
Output:
['I-am-the ', 'ugliest-person']
List = ['test test test ', 'test y jk ']
lenght = len(List)
i = 0
while i < lenght:
List[i] = List[i].replace(' ', '-')
i += 1
print(List)
I have list of
List=[{'ManufStr': '',
'ProdStr': 'QWER1025',
'SerialNum': 'ABCDEF0123456789',
'VendorID': '0xa34',
'ProdID': '0x4007'},
{'ManufStr': '',
'ProdStr': 'ASDF452x',
'SerialNum': 'ABCDEF0123456789',
'VendorID': '0xa34',
'ProdID': '0x4007'}]
How can i get the values of VendorID, ProdID and ProdStr and then join them all together to make one string string?
such as VID0xa34&PID0x4007 ASDF452x
Try this:
>>> ['VID' + item['VendorID'] + '&PID' + item['ProdID'] + ' ' + item['ProdStr'] for item in List]
For the List you provided above it will output:
['VID0xa34&PID0x4007 QWER1025', 'VID0xa34&PID0x4007 ASDF452x']
Hope it helps!
You need to loop through the dictionaries in the list.
for item in List:
print "VID{}&PID{} {}".format(
item["VendorID"], item["ProdID"], item["ProdStr"])
What aboud string template and list comprehension?
infos = ( 'VID{}&PID{} {}'.format(item['VendorID'], item['ProdID'], item['ProdStr']) for item in List )
`print ['VID' + item['VendorID'] + '&PID' + item['ProdID'] + ' ' + item["ProdStr"] for item in List]`
Output: ['VID0xa34PID0x4007 QWER1025', 'VID0xa34PID0x4007 ASDF452x']
Try somethinglike this,
result = []
for item in List:
all_string = "VID{}&PID{}{}".format(item['VendorID'], item['ProdID'], item['ProdStr'])
result.append(all_string)
I have a list of strings. I need to add a string to all of them, and then a second string to only two of them. I am trying the following:
[s + ' help ' for s in [ ['me '].extend(['with ' + t for t in ['things', 'please']]) ] ]
What I would expect is the following:
['me help ', 'with things help ', 'with please help ']
Nothing happens when I try to run this in iPython. It seems to have a problem with using the extend method on a 'newly created' list. I am unsure, and relatively new to python.
EDIT:
To be more explicit, in the above example, the original list would be:
['me', 'things', 'please']
I need to add 'help ' to all of them, and 'with ' to only the latter two.
And I get an error when running the above line of code:
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
Second Edit:
I am more focused on the location of the elements. I want a string added to every element of the list, excluding the first, and then a second string added to the entire new list. My above approach was a first stab at what it should be (in the most 'pythonic' way), but it does not work. I understand why it does not work, but I am unsure how to rewrite the above line into something that will work.
In case you want to index the elements in the list you can use this:
s=['me', 'things', 'please']
['with ' + x + ' help' if x!=s[0] else x+' help' for x in s]
Unless you define a function, which extends a list and returns the result:
def lext(l, lx):
l.extend(lx)
return l
(which python already does):
import itertools
lext = itertools.chain
and employ it this way:
[s + ' help ' for s in lext(['me '], ['with ' + t for t in ['things', 'please']])]
you have to do it step by step:
inp = ['me', 'things', 'please']
out1 = [ s + ' help' for s in inp]
out2 = [ out1[0] ]
out2.extend(('with ' + s for s in out1[1:]))
Welcome to the wonderful world of procedures and functions, aka. commands and expressions :)
This is a possible solution to achieve exactly what you wrote you expect:
items = ['me', 'things', 'please']
new_items = []
for index, value in enumerate(items):
# Prepend to every item but the first
if i > 0:
v = "with %s" % v
# Append to every item
v = "%s help " % v
new_items.append(v)
print(new_items) # outputs: ['me help ', 'with things help ', 'with please help ']
This appends help to every item, and prepends with to every but the first item.
I think I figured this out. Thanks all for your help, but this is (most simply) what I was trying to get at:
[s + ' help ' for s in ['me '] + ['with ' + t for t in ['things', 'please']] ]
which produces
['me help ', 'with things help ', 'with please help ']
It was just the extend method that I needed to replace with + to concatenate the list.
If it's string match based:
['with ' + t + ' help' if t != 'me' else t + ' help' for t in ['me', 'things', 'please']]
This will create a list of strings based if an item is me or not.
Produces:
['me help', 'with things help', 'with please help']
If it's positional:
If you always know the position, this might help:
x = ['me', 'things', 'please']
word_pos = 1
['{} help'.format(i) for i in x[:word_pos]] + ['with {} help'.format(i) for i in x[word_pos:]]
Which produces:
['me help', 'with things help', 'with please help']
Either one can be a one-liner, but I'd strongly suggest expanding these as they quickly get fudgy to work with.