Python adding to the list - python

I have to strip whitespace for extracted strings, one string at a time for which I'm using split(). The split() function returns list after removing white spaces. I want to store this in my own dynamic list since I have to aggregate all of the strings.
The snippet of my code:
while rec_id = "ffff"
output = procs.run_cmd("get sensor info", command)
sdr_li = []
if output:
byte_str = output[0]
str_1 = byte_str.split(' ')
for byte in str_1:
sdr_li.append(byte)
rec_id = get_rec_id()
Output = ['23 0a 06 01 52 2D 12']
str_1 = ['23','0a','06','01','52','2D','12']
This does not look very elegant, transferring from one list to another. Is there another way to achieve this.

list.extend():
sdr_li.extend(str_1)

str.split() returns you a list so just add your list's items to the main list. Use extend https://docs.python.org/2/tutorial/datastructures.html
so rewriting your data into something legible and properly indented you'd get:
my_list = list
while rec_id = "ffff"
output = procs.run_cmd("get sensor info", command)
if output:
result_string = output[0]
# extend my_list with the list resulting from the whitespace
# seperated tokens of the output
my_list.extend( result_string.split() )
pass # end if
rec_id = get_rec_id()
...
pass # end while

Related

Remove Prefixes From a String

What's a cute way to do this in python?
Say we have a list of strings:
clean_be
clean_be_al
clean_fish_po
clean_po
and we want the output to be:
be
be_al
fish_po
po
Another approach which will work for all scenarios:
import re
data = ['clean_be',
'clean_be_al',
'clean_fish_po',
'clean_po', 'clean_a', 'clean_clean', 'clean_clean_1']
for item in data:
item = re.sub('^clean_', '', item)
print (item)
Output:
be
be_al
fish_po
po
a
clean
clean_1
Here is a possible solution that works with any prefix:
prefix = 'clean_'
result = [s[len(prefix):] if s.startswith(prefix) else s for s in lst]
You've merely provided minimal information on what you're trying to achieve, but the desired output for the 4 given inputs can be created via the following function:
def func(string):
return "_".join(string.split("_")[1:])
you can do this:
strlist = ['clean_be','clean_be_al','clean_fish_po','clean_po']
def func(myList:list, start:str):
ret = []
for element in myList:
ret.append(element.lstrip(start))
return ret
print(func(strlist, 'clean_'))
I hope, it was useful, Nohab
There are many ways to do based on what you have provided.
Apart from the above answers, you can do in this way too:
string = 'clean_be_al'
string = string.replace('clean_','',1)
This would remove the first occurrence of clean_ in the string.
Also if the first word is guaranteed to be 'clean', then you can try in this way too:
string = 'clean_be_al'
print(string[6:])
You can use lstrip to remove a prefix and rstrip to remove a suffix
line = "clean_be"
print(line.lstrip("clean_"))
Drawback:
lstrip([chars])
The [chars] argument is not a prefix; rather, all combinations of its values are stripped.

regarding list object's attributes

While I am writing this code lst=list(map(int,input().split().strip())) then I am getting an AttributeError 'list' object has no attribute strip
But it is working when I remove the strip() method.
My question is that list object also has no attribute split. So in this case (lst=list(map(int,input().split())) why it is not giving any error and why it is giving error in case of strip() method?
Before you read the rest of the answer: you shouldn't have to strip() after you call split() because split() will consider multiple whitespace characters as a single delimiter and automatically remove the extra whitespace. For example, this snippet evaluates to True:
s1 = "1 2 3"
s2 = "1 2 3"
s3 = " 1 2 3 "
s1.split() == s2.split() == s3.split()
split() and strip() are both attributes of string objects!
When you're confused by code that's been stuffed into one line, it often helps to unravel that code out over multiple lines to understand what it's doing
Your line of code can be unraveled like so:
user_input_str = input()
split_input_list = user_input_str.split()
stripped_input = split_input_list.strip() ### ERROR!!!
lst = list(map(int, stripped_input))
Clearly, you tried to access the strip() method of a list object, and you know that doesn't exist.
In your second example, you do
user_input_str = input()
split_input_list = user_input_str.split()
lst = list(map(int, split_input_list))
Which works perfectly fine because you don't try to access strip() on a list object
Now to fix this, you need to change the order of operations: first, you get your input. Next, strip it. This gives you back a string. Then, split this stripped string.
user_input_str = input()
stripped_input_str = user_input_str.strip() ### No error now!
split_input_list = stripped_input_str.split()
lst = list(map(int, split_input_list))
#or in one line:
lst = list(map(int, input().strip().split()))
Or, if you want to strip each element of the split input list, you will need to map the strip() function to split_input_list like so:
user_input_str = input()
split_input_list = user_input_str.split()
stripped_input_list = list(map(str.strip, split_input_list))
lst = list(map(int, stripped_input_list))
#or in one line
lst = list(map(int, map(str.strip, input().split())))
# or, create a function that calls strip and then converts to int, and map to it
def stripint(value):
return int(value.strip())
lst = list(map(stripint, input().split()))

How to turn a list containing strings into a list containing integers (Python)

I am optimizing PyRay (https://github.com/oscr/PyRay) to be a usable Python ray-casting engine, and I am working on a feature that takes a text file and turns it into a list (PyRay uses as a map). But when I use the file as a list, it turns the contents into strings, therefore not usable by PyRay. So my question is: How do I convert a list of strings into integers? Here is my code so far. (I commented the actual code so I can test this)
print("What map file to open?")
mapopen = input(">")
mapload = open(mapopen, "r")
worldMap = [line.split(',') for line in mapload.readlines()]
print(worldMap)
The map file:
1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,
2,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,2,0,0,3,0,0,0,0,0,0,0,2,3,2,3,0,0,2,
2,0,3,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,2,
2,3,1,0,0,2,0,0,0,2,3,2,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,1,0,1,0,0,1,2,0,0,0,2,
2,0,0,0,0,0,0,0,0,2,0,2,0,0,2,1,0,0,0,1,
1,0,0,0,0,0,0,0,0,1,3,1,0,0,0,0,0,0,0,2,
2,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,2,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,2,
2,0,3,0,0,2,0,0,0,0,0,0,0,2,3,2,1,2,0,1,
1,0,0,0,0,3,0,0,0,0,0,0,0,1,0,0,2,0,0,2,
2,3,1,0,0,2,0,0,2,1,3,2,0,2,0,0,3,0,3,1,
1,0,0,0,0,0,0,0,0,3,0,0,0,1,0,0,2,0,0,2,
2,0,0,0,0,0,0,0,0,2,0,0,0,2,3,0,1,2,0,1,
1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,3,0,2,
2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,1,
2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,
Please help me, I have been searching all about and I can't find anything.
try this: Did you want a list of lists? or just one big list?
with open(filename, "r") as txtr:
data = txtr.read()
data = txtr.split("/n") # split into list of strings
data = [ list(map(int, x.split(","))) for x in data]
fourth line splits string into list by removing comma, then appliea int() on each element then turns it into a list. It does this for every element in data. I hope it helps.
Here is for just one large list.
with open(filename, "r") as txtr:
data = txtr.readlines() # remove empty lines in your file!
data = ",".join(data) # turns it into a large string
data = data.split(",") # now you have a list of strings
data = list(map(int, data)) # applies int() to each element in data.
Look into the map built-in function in python.
L=['1', '2', '3']
map = map(int, L)
for el in map:
print(el)
>>> 1
... 2
... 3
As per you question, please find below a way you can change list of strings to list of integers (or integers if you use list index to get the integer value). Hope this helps.
myStrList = ["1","2","\n","3"]
global myNewIntList
myNewIntList = []
for x in myStrList:
if(x != "\n"):
y = int(x)
myNewIntList.append(y)
print(myNewIntList)

Python Joining List and adding and removing characters

I have a list i need to .join as string and append characters
my_list = ['3.3.3.3', '2.2.2.3', '2.2.2.2']
my_list.append(')"')
my_list.insert(0,'"(')
hostman = '|'.join('{0}'.format(w) for w in my_list)
#my_list.pop()
print(hostman)
print(my_list)
My output = "(|3.3.3.3|2.2.2.3|2.2.2.2|)"
I need the output to be = "(3.3.3.3|2.2.2.3|2.2.2.2)"
how can i strip the first and last | from the string
You are making it harder than it needs to be. You can just use join() directly with the list:
my_list = ['3.3.3.3', '2.2.2.3', '2.2.2.2']
s = '"(' + '|'.join(my_list) + ')"'
# s is "(3.3.3.3|2.2.2.3|2.2.2.2)"
# with quotes as part of the string
or if you prefer format:
s = '"({})"'.format('|'.join(my_list))
Try this :
hostman = "("+"|".join(my_list)+")"
OUTPUT :
'(3.3.3.3|2.2.2.3|2.2.2.2)'

sorting a list and separating the different features

So I am given a list and I am supposed to sort it down into two lists, one with the names of the companies and one with the prices in a nested list.
['Acer 481242.74\n', 'Beko 966071.86\n', 'Cemex 187242.16\n', 'Datsun 748502.91\n', 'Equifax 146517.59\n', 'Gerdau 898579.89\n', 'Haribo 265333.85\n']
I used the following code to separate the names properly:
print('\n'.join(data))
namelist = [i.split(' ', 1)[0] for i in data]
print(namelist)
But now it wants me to seperate all the prices from the list and put them in a single list nested together and I don't know how to do that.
To build two separate lists, just use a regular loop:
names = []
prices = []
for entry in data:
name, price = entry.split()
names.append(name)
prices.append(price)
If you needed the entries together in one list, each entry a list containing the name and the price separately, just split in a list comprehension like you did, but don't pick one or the other value from the result:
names_and_prices = [entry.split() for entry in data]
I used str.split() without arguments to split on arbitrary whitespace. This assumes you always have exactly two entries in your strings. You can still limit the split, but then use None as the first argument, and strip the line beforehand to get rid of the \n separately:
names_and_prices = [entry.strip().split(None, 1) for entry in data]
Demo for the 'nested' approach:
>>> data = ['Acer 481242.74\n', 'Beko 966071.86\n', 'Cemex 187242.16\n', 'Datsun 748502.91\n', 'Equifax 146517.59\n', 'Gerdau 898579.89\n', 'Haribo 265333.85\n']
>>> [entry.split() for entry in data]
[['Acer', '481242.74'], ['Beko', '966071.86'], ['Cemex', '187242.16'], ['Datsun', '748502.91'], ['Equifax', '146517.59'], ['Gerdau', '898579.89'], ['Haribo', '265333.85']]
split() is the right approach, as it will give you everything you need if you don't limit it to just one split (the , 1) in your code). If you provide no arguments to it at all, it'll split on any size of whitespace.
>>> data = ['Acer 481242.74\n', 'Beko 966071.86\n', 'Cemex 187242.16\n', 'Datsun 748502.91\n', 'Equifax 146517.59\n', 'Gerdau 898579.89\n', 'Haribo 265333.85\n']
>>> nested_list = [i.split() for i in data]
>>> nested_list
[['Acer', '481242.74'], ['Beko', '966071.86'], ['Cemex', '187242.16'], ['Datsun', '748502.91'], ['Equifax', '146517.59'], ['Gerdau', '898579.89'], ['Haribo', '265333.85']]
>>> print(*nested_list, sep='\n')
['Acer', '481242.74']
['Beko', '966071.86']
['Cemex', '187242.16']
['Datsun', '748502.91']
['Equifax', '146517.59']
['Gerdau', '898579.89']
['Haribo', '265333.85']

Categories