Append or Add to string of specific index - python

I have a list of class objects 'x'. I am trying to create a new list by appending certain attribute values of the objects but I would like to append more that one attribute per index. For example, what I currently get:
x = blah.values()
newList = []
for i in range(len(x)):
if x[i].status == 'ACT':
newList.append(str(x[i].full_name)),
newList.append(str(x[i].team))
else:
pass
print newList
The above code provides me with something like:
['Victor Cruz', 'NYG', 'Marcus Cromartie', 'SF',....]
What I am trying to get:
['Victor Cruz NYG', 'Marcus Cromartie SF',....]
How can I append more than one attribute per index? Hope this make sense, I can try to further elaborate if needed, thanks!

You can use .format() in order to format your string. Notice the space between {} {}
for i in range(len(x)):
if x[i].status == 'ACT':
newList.append("{} {}".format(x[i].full_name,x[i].team) )
Another way is using "%s" % string notation
newList.append("%s %s" % (str(x[i].full_name),str(x[i].team)))
Another example of .format using.
"{} is {}".format('My answer', 'good')
>>> "My answer is good"

You could put the items into one string using .format() and append the string once:
for i in range(len(x)):
if x[i].status == 'ACT':
newList.append('{} {}'.format(x[i].full_name, x[i].team))
On a lighter note, using a list comprehension is a great alternative for creating your list:
newList = ['{} {}'.format(o.full_name, o.team) for o in blah.values() if o.status == 'ACT']
You'll notice that range and len are no longer used in the comprehension, and there is no longer need for indexing.

Related

Change a list separator delimiter to another (python)

I need help using Python.
Supposing I have the list [22,23,45].
Is it possible to get an output like this: [22;23:45] ?
It's possible to change the delimiters if you display your list as a string. You can then use the join method. The following example will display your list with ; as a delimiter:
print(";".join(my_list))
This will only work if your list's items are string, by the way.
Even if you have more than one item
str(your_list[:1][0])+";" + ":".join(map(str,your_list[1:])) #'22;23:45'
Not sure why you want to wrap in the list but if you do just wrap around the above string in list()
my list which was [22,23,45] returned [;2;2;,; ;2;3;,; ;4;5;,] for both methods.
To bring more information, I have a variable:
ID= [elements['id'] for elements in country]
Using a print (ID), I get [22,23,45] so I suppose that the list is already to this form.
Problem is: I need another delimiters because [22,23,45] corresponds to ['EU, UK', 'EU, Italy', 'USA, California'].
The output I wish is [22,23,45] --> ['EU, UK'; 'EU, Italy'; 'USA, California']
I don't know if it's clearer but hope it could help
Try this I don't know exactly what do You want?
first solution:
list = [22,23,45]
str = ""
for i in list:
str += "{}{}".format(i, ";")
new_list=str[:-len(";")]
print(new_list)
and this is second solution
list = [22,23,45]
print(list)
list=str(list)
list=list.split(",")
list=";".join(list)
print(list)

Split a list from some element and getting the item values into another list in Python 2.7

This is my list:
l = ['today','is','a','holiday','but','nothing','to','do']
I wish to put the items after 'but' into another list such as:
another_list = ['nothing','to','do']
I tried the following way:
l = ['today','is','a','holiday','but','nothing','to','do']
for element in l:
parts = element.split('but')
But it does not provide the output I expected.
You are splitting on an array element not a string.. so in this case you a split isn't going to work. There is nothing to split. Instead find the index and continue from there. Checkout https://www.tutorialspoint.com/python/python_lists.htm to learn more about python list
l = ['today','is','a','holiday','but','nothing','to','do']
# get the index of but
i = l.index("but") # "This method returns index of the found object otherwise raise an exception indicating that value does not find."
# print everything after "but" using slice logic.
print l[i+1:]
You can use index:
l[l.index('but')+1:]
>>> ['nothing', 'to', 'do']
Join the list, partition it, and then re-split it.
' '.join(l).partition('but')[-1].split() # ['nothing', 'to', 'do']

How to add two odd lists into one list in python?

I am very new to Python, and I'm trying to combine elements from two lists and produce a string from the combination.
My variables are:
fro = ['USD']
to = ['AUD', 'CAD', 'EUR']
I want output like this in a string:
pairs = "USDAUD,USDCAD,USDEUR"
Thanks a ton in advance for your help.
Why not use a generator expression like this:
fro = ['USD']
to = ['AUD', 'CAD', 'EUR']
pairs = ','.join(fro[0] + x for x in to)
Note that from is a reserved keyword and is thus not a valid variable name.
Output:
>>>pairs
'USDAUD,USDCAD,USDEUR'
If you were ever curious as to whether something you wish to use as a variable name is a keyword (and thus an illegal variable name) or not, you can always check with something like this:
>>> import keyword
>>> keyword.iskeyword("from")
True
Elizion's answer is nice and succinct, but as a beginner you may want to approach it without using an intermediate/advanced structure like a generator:
fro = ['USD']
to = ['AUD', 'CAD', 'EUR']
pairs = ""
for word in to:
pairs += fro[0] + word + ","
Removing the trailing comma:
pairs = pairs[:-1]
Elizion is absolutely correct.
If you have list elements varies dynamically, you can use this line:
absolutely pythonic way!!
pair_elem = ','.join('%s%s' % (x, y) for y in to for x in fro)
And conventional way is like, iterate list elems:
for multiple in to:
for single in fro:
pairs = ",".join(single + multiple)

Python procedure to populate dictionary from data in 2 separate lists

I am trying to create an automated python procedure that uses two separate lists to create a dictionary and so far I am failing. I have two sorted lists where the nth item in the fist list corresponds to the nth item in the second list and I want to combine them into a dictionary.
For example, a subset of the 2 lists are as follows;
name = ['Adam', 'Alfred', 'Amy', 'Andy', 'Bob']
year = [1972, 1968, 1985, 1991, 1989]
I would want my output to be:
birth_years = {'Adam':1972, 'Alfred':1968, 'Amy':1985, 'Andy':1991, 'Bob':1989}
I was trying to do this with a for loop, but I could not get it to work. I appreciate any help.
Use the zip and dict functions to construct a dictionary out of a list of tuples:
birth_years = dict(zip(name, year))
And if you're curious, this would be how I would try to do it with a for loop:
birth_years = {}
for index, n in enumerate(name):
birth_years[n] = years[index]
I think I like the first example more.
birth_years = {}
for i in range(len(name)):
birth_years[name[i]] = year[i]
Try a dictionary comprehension:
birth_years = {nm:year[idx] for idx, nm in enumerate(name)}
Your lists would be better named names and years. You got off to a good start by trying to do it with a for loop. Most practical data processing problems involve error checking, which is just a tad difficult with one-liners. Example:
birth_years = {}
for i, name in enumerate(names):
if name in birth_years:
log_duplicate(i, name, years[i]))
else:
birth_years[name] = years[i]

How to compare an element of a tuple (int) to determine if it exists in a list

I have the two following lists:
# List of tuples representing the index of resources and their unique properties
# Format of (ID,Name,Prefix)
resource_types=[('0','Group','0'),('1','User','1'),('2','Filter','2'),('3','Agent','3'),('4','Asset','4'),('5','Rule','5'),('6','KBase','6'),('7','Case','7'),('8','Note','8'),('9','Report','9'),('10','ArchivedReport',':'),('11','Scheduled Task',';'),('12','Profile','<'),('13','User Shared Accessible Group','='),('14','User Accessible Group','>'),('15','Database Table Schema','?'),('16','Unassigned Resources Group','#'),('17','File','A'),('18','Snapshot','B'),('19','Data Monitor','C'),('20','Viewer Configuration','D'),('21','Instrument','E'),('22','Dashboard','F'),('23','Destination','G'),('24','Active List','H'),('25','Virtual Root','I'),('26','Vulnerability','J'),('27','Search Group','K'),('28','Pattern','L'),('29','Zone','M'),('30','Asset Range','N'),('31','Asset Category','O'),('32','Partition','P'),('33','Active Channel','Q'),('34','Stage','R'),('35','Customer','S'),('36','Field','T'),('37','Field Set','U'),('38','Scanned Report','V'),('39','Location','W'),('40','Network','X'),('41','Focused Report','Y'),('42','Escalation Level','Z'),('43','Query','['),('44','Report Template ','\\'),('45','Session List',']'),('46','Trend','^'),('47','Package','_'),('48','RESERVED','`'),('49','PROJECT_TEMPLATE','a'),('50','Attachments','b'),('51','Query Viewer','c'),('52','Use Case','d'),('53','Integration Configuration','e'),('54','Integration Command f'),('55','Integration Target','g'),('56','Actor','h'),('57','Category Model','i'),('58','Permission','j')]
# This is a list of resource ID's that we do not want to reference directly, ever.
unwanted_resource_types=[0,1,3,10,11,12,13,14,15,16,18,20,21,23,25,27,28,32,35,38,41,47,48,49,50,57,58]
I'm attempting to compare the two in order to build a third list containing the 'Name' of each unique resource type that currently exists in unwanted_resource_types. e.g. The final result list should be:
result = ['Group','User','Agent','ArchivedReport','ScheduledTask','...','...']
I've tried the following that (I thought) should work:
result = []
for res in resource_types:
if res[0] in unwanted_resource_types:
result.append(res[1])
and when that failed to populate result I also tried:
result = []
for res in resource_types:
for type in unwanted_resource_types:
if res[0] == type:
result.append(res[1])
also to no avail. Is there something i'm missing? I believe this would be the right place to perform list comprehension, but that's still in my grey basket of understanding fully (The Python docs are a bit too succinct for me in this case).
I'm also open to completely rethinking this problem, but I do need to retain the list of tuples as it's used elsewhere in the script. Thank you for any assistance you may provide.
Your resource types are using strings, and your unwanted resources are using ints, so you'll need to do some conversion to make it work.
Try this:
result = []
for res in resource_types:
if int(res[0]) in unwanted_resource_types:
result.append(res[1])
or using a list comprehension:
result = [item[1] for item in resource_types if int(item[0]) in unwanted_resource_types]
The numbers in resource_types are numbers contained within strings, whereas the numbers in unwanted_resource_types are plain numbers, so your comparison is failing. This should work:
result = []
for res in resource_types:
if int( res[0] ) in unwanted_resource_types:
result.append(res[1])
The problem is that your triples contain strings and your unwanted resources contain numbers, change the data to
resource_types=[(0,'Group','0'), ...
or use int() to convert the strings to ints before comparison, and it should work. Your result can be computed with a list comprehension as in
result=[rt[1] for rt in resource_types if int(rt[0]) in unwanted_resource_types]
If you change ('0', ...) into (0, ... you can leave out the int() call.
Additionally, you may change the unwanted_resource_types variable into a set, like
unwanted_resource_types=set([0,1,3, ... ])
to improve speed (if speed is an issue, else it's unimportant).
The one-liner:
result = map(lambda x: dict(map(lambda a: (int(a[0]), a[1]), resource_types))[x], unwanted_resource_types)
without any explicit loop does the job.
Ok - you don't want to use this in production code - but it's fun. ;-)
Comment:
The inner dict(map(lambda a: (int(a[0]), a[1]), resource_types)) creates a dictionary from the input data:
{0: 'Group', 1: 'User', 2: 'Filter', 3: 'Agent', ...
The outer map chooses the names from the dictionary.

Categories