retain only 1 item in a list per unique prefix - python-3.x

I have an example situation where I have a list as follows:
test = ['a-nyc','a-chi','b-sf','c-dal','a-phx','c-la']
the items in this list are naturally ordered in some way, and the objective is to keep the first encountered value for each prefix, e.g. the desired result is a list as follows:
['a-nyc', 'b-sf', 'c-dal']
is there a handy way of doing this?
looks like this can be done this way:
newl = []
prel = []
for i in range(len(test)):
if test[i].split('-')[0] not in prel:
newl.append(test[i])
else:
pass
prel.append(test[i].split('-')[0])
but not sure if there is a more pythonic solution

Yes, you can try like following also:
test = ['a-nyc','a-chi','b-sf','c-dal','a-phx','c-la']
prefix = []
newlist = []
for i in test:
if i.split('-')[0] not in prefix:
prefix.append(i.split('-')[0])
newlist.append(i)
print(newlist)
In this, if any query then let me know.
Thank you.

Related

Elements within a list of lists

I have a below mentioned list:
a= ['1234,5678\n','90123,45678\n']
The expected output I'm working towards is this:
op = [['1234','5678'],['90123','45678']]
Basically a list of lists with individual elements referring to a particular column.
Using the below mentioned code i get the following output:
a = ['1234,5678\n','90123,45678\n']
new_list = []
for element in a:
#remove new lines
new_list.append(element.splitlines())
print(new_list)
output:[['1234,5678'], ['90123,45678']]
Any direction regarding this would be much appreciated.
Check this:
a= ['1234,5678\n','90123,45678\n']
a = ['1234,5678\n','90123,45678\n']
new_list = []
for element in a:
#remove new lines
new_list.append(element.strip("\n").split(","))
print(new_list)
Try this:
a = [i.strip("\n").split(",") for i in a]
Since the strings in your input list appears to follow the CSV format, you can use csv.reader to parse them:
import csv
list(csv.reader(a))
This returns:
[['1234', '5678'], ['90123', '45678']]

Python pattern auto matching within the list

I am trying to write a small script to group strings with similar patterns together. The following is my program snippet, which is working fine, but a little inaccurate.
lst = ["report-2020.10.13", "report-2020.12.12", "analytics-2020.12.14", "sales-cda87", "analytics-2020.11.21", "sales-vu7sa"]
final = []
for pat in lst:
pat = pat[:len(pat) // 2]
ils = []
for pat2 in lst:
if pat2.startswith(pat):
ils.append(pat2)
final.append(tuple(ils))
finalls = list(set(final))
for f in finalls:
print(f)
Also, I want the exact string pattern that groups the string. For example, from string list ["rep-10-01", "rep-10-02", "rep-11-06"] I want "rep-" as a pattern.
Are there any improvements required? Or any libraries/modules that can help me out in first as well as second problem?
Thanks in advance.
Does this work as you expected:
from collections import defaultdict
res = defaultdict(str)
lst = ["report-2020.10.13", "report-2020.12.12", "analytics-2020.12.14",
"sales-cda87", "analytics-2020.11.21", "sales-vu7sa"]
#ll = ['rep-10-01', 'rep-10-02', 'rep-11-06']
for pat in lst:
pattern = pat.split('-')
#print(pattern[0]) # real pattern - eg. report, sales, analytics
res[pattern[0]] += pat+ ', '
print(res)
Output:
defaultdict(<class 'str'>, {'report': 'report-2020.10.13, report-2020.12.12, ', 'analytics': 'analytics-2020.12.14, analytics-2020.11.21, ', 'sales': 'sales-cda87, sales-vu7sa, '})

How to take in a string and use it as a variable assigning it an empty list

So here is what I want to do...:
I have a keyList = ['age', 'occupation', 'education']
and I want to create this:
age = []
occupation = []
education = []
and the elements of keyList are arbitrary and if the words were to change then the list names were to change as well.
How would I code this?
Not a hardcore python programmer, just taking first year computing. Hopefully nothing too complicated to understand.
This is the link for a picture of the assignment details:
https://imgur.com/a/8YjAHlH
Here's one way to do that:
>>> key_list = ['age', 'occupation', 'education']
>>> for key in key_list:
... exec(f'{key} = []')
...
>>> age
[]
On the other hand, I'm not sure this is exactly what you want/need to do, and using exec or eval is often recommended against.

How do I remove the first element in a list without using the del/pop/splicing/index/remove/find methods?

I'm new to programming and I'm having some trouble with my code. I need to remove the first element in a list without using any of the mentioned methods. What I have so far:
user_string = str(input("Enter a one-character string"))
user_string = user_string.lower()
user_list = [1,2,3]
def choiceN(user_list): #goes to this function if the user enters n as user_string
temp_list = []
for i in range(1, len(user_list)):
temp_list.append(user_list[i])
return temp_list
I don't see where this is going wrong. As I'm new to programming, any explanations would also be greatly appreciated. Thank you.
Make a copy of the list for only the 2nd element to last element and delete the first list.

Python 3.2 split the string values in a list

I have a list like below:
rawinput = ['corp\\asre', 'corp\\banjar', 'corp\\bicknk', 'corp\\daniele']
I want to be able to do
users = []
users = rawinput.split(",")
print(users)
How do I do this in Python 3.2? Thanks.
What you have,
rawinput = ['corp\\asre', 'corp\\banjar', 'corp\\bicknk', 'corp\\daniele']
is a list of strings already. You can just iterate through it as a list. You don't need to split anything.
If you had something like this,
rawinput = "corp\\asre, corp\\banjar, corp\\bicknk, corp\\daniele"
rawinput.split(',') would return the above list.
split() is applied on string, in return it gives you a list[] which contains the substring as elements in order of the parent string.
In your case:
input = "corp\\asre, corp\\banjar, corp\\bicknk, corp\\daniele"
input.split(',')
will return
['corp\\asre', 'corp\\banjar', 'corp\\bicknk', 'corp\\daniele']

Resources