To append an element into a list without generating any other elements - python-2.7

Trying to append an element into an empty list as follows, while appending it also adds a character 'u' like [u'slice'] into the empty list while adding an element into the list, however expected is ['slice']
Code as follows:
type = slice # value for type
value = []
value.append(type)
Output:
value = [u'slice']
Requesting people for help to get output as ['slice'].

For some reason the output is in Unicode, hence the u. Try re-encoding it to ascii
by using .encode("ascii"). Sorry I don't know why it's doing that though.

Related

How do I remove duplicated elements from a python array?

What I just want to achieve is to be able to get a list with elemnts that aren't repeating
<current state>
results = ["Anna","Michael","Anna","Juliet","Juliet", "Anna"]
<expectation>
results=["Anna","Michael", "Juliet"]
The following will remove duplicates.
results = ["Anna","Michael","Anna","Juliet","Juliet", "Anna"]
results = list(dict.fromkeys(results))
print(results)
Output:
['Anna', 'Michael', 'Juliet']
See https://www.w3schools.com/python/python_howto_remove_duplicates.asp for more information.
You can conver the list to a set, which has no duplicates by definition.
results = set(["Anna","Michael","Anna","Juliet","Juliet", "Anna"])
If you need the type of the result to be a list, you can simply convert it back:
results = list(set(["Anna","Michael","Anna","Juliet","Juliet", "Anna"]))

How to show which values of one list are in other list?

Having 2 lists, I want check which values of List1 are in List2. I'm trying as below but I get error
List1 = {3,2,8,7,5}
List2 = {1,3,4,2,6,7,9}
= List.Transform(List1, each Text.Contains(List2, _))
Expression.Error: We cannot convert a value of type List to type Text.
Details:
Value=[List]
Type=[Type]
My expected output would be 3,2,7.
How can I do this?
See List.Intersect Documentation
Intersect = List.Intersect({List1,List2})
#horseyride has probably the best answer but using your original logic, you could also write the intersection like this:
List.Select(List1, each List.Contains(List2, _))
This uses Select instead of Transform since you are trying to select/filter instead of changing the elements and uses the appropriate List type instead of Text for the Contains part.

Removes braces from variable

I am comparing two list:
gp_yu = set(agencys_sp2).intersection(gp_list_t)
the output is in braces like this {900}. What can i do to remove the braces
You can obtain an element from an iterable iterable (a set is an iterable, but lists, dictionaries, etc. are iterables as well) with:
element = next(iter(iterable))
In case the iterable contains two or more elements, it will return the first element (a set has no really a "first" element in the sense that the order can very over time, but it will return an element).
In case the iterable contains no elements at all (an empty set, list, tuple, dictionary, etc.), then it will raise a StopIteration error. You can however let the expression return a default value with:
element = next(iter(iterable), default)
So in case iterable contains one or more elements, the "first" element is returned, in case it is empty, it will return default.
Probably you mean some like how to get your set as a string, so just use join function.
Some like this ', '.join(gp_yu).
Check this topic for more information:
Python: how to join entries in a set into one string?

Compare a portion of String value present in 2 Lists

Below code extract a particular value from List srchlist and check for a particular value in List rplzlist. The contents of list srchlist and rplzlist looks like below.
srchlist = ["DD='A'\n", "SOUT='*'\n", 'PGM=FTP\n', 'PGM=EMAIL']
rplzlist = ['A=ZZ.VVMSSB\n', 'SOUT=*\n', 'SALEDB=TEST12']
I am extracting the characters after the '='(equal) sign and within the single quotes using a combination of strip and translate function.
Of the elements in the srchlist only the 'SOUT' matches with the rplzlist.
Do let me know why the below code does not work, also suggest me a better approach to compare a part of string present in the list.
for ele in srchlist:
sYmls = ele.split('=')
vAlue = sYmls[1].translate(None,'\'')
for elem in rplzlist:
rPls = elem.split('=')
if vAlue in rPls:
print("vAlue")
Here is the more pythonic approach for what you wanted to do:
>>> list(set([(i.split('='))[1].translate(None,'\'') for i in srchlist]) & set([j.split('=')[1] for j in rplzlist]))
['*\n']
I used set() and then get the whole output as list, you may use .join().
Inside set(), list comprehension is given which is faster than the normal for loops.
Another Solution Using join(), and replace() in place of translate():
>>> "".join(set([(i.split('='))[1].replace('\'','') for i in srchlist]) & set([j.split('=')[1] for j in rplzlist]))
'*\n'

TypeError during executemany() INSERT statement using a list of strings

I am trying to just do a basic INSERT operation to a PostgreSQL database through Python via the Psycopg2 module. I have read a great many of the questions already posted regarding this subject as well as the documentation but I seem to have done something uniquely wrong and none of the fixes seem to work for my code.
#API CALL + JSON decoding here
x = 0
for item in ulist:
idValue = list['members'][x]['name']
activeUsers.append(str(idValue))
x += 1
dbShell.executemany("""INSERT INTO slickusers (username) VALUES (%s)""", activeUsers
)
The loop creates a list of strings that looks like this when printed:
['b2ong', 'dune', 'drble', 'drars', 'feman', 'got', 'urbo']
I am just trying to have the code INSERT these strings as 1 row each into the table.
The error specified when running is:
TypeError: not all arguments converted during string formatting
I tried changing the INSERT to:
dbShell.executemany("INSERT INTO slackusers (username) VALUES (%s)", (activeUsers,) )
But that seems like it's merely treating the entire list as a single string as it yields:
psycopg2.DataError: value too long for type character varying(30)
What am I missing?
First in the code you pasted:
x = 0
for item in ulist:
idValue = list['members'][x]['name']
activeUsers.append(str(idValue))
x += 1
Is not the right way to accomplish what you are trying to do.
first list is a reserved word in python and you shouldn't use it as a variable name. I am assuming you meant ulist.
if you really need access to the index of an item in python you can use enumerate:
for x, item in enumerate(ulist):
but, the best way to do what you are trying to do is something like
for item in ulist: # or list['members'] Your example is kinda broken here
activeUsers.append(str(item['name']))
Your first try was:
['b2ong', 'dune', 'drble', 'drars', 'feman', 'got', 'urbo']
Your second attempt was:
(['b2ong', 'dune', 'drble', 'drars', 'feman', 'got', 'urbo'], )
What I think you want is:
[['b2ong'], ['dune'], ['drble'], ['drars'], ['feman'], ['got'], ['urbo']]
You could get this many ways:
dbShell.executemany("INSERT INTO slackusers (username) VALUES (%s)", [ [a] for a in activeUsers] )
or event better:
for item in ulist: # or list['members'] Your example is kinda broken here
activeUsers.append([str(item['name'])])
dbShell.executemany("""INSERT INTO slickusers (username) VALUES (%s)""", activeUsers)