I'm just wondering how to convert a list of strings into a nested list? without module import.
for example:
input ["ABC","1","x","y","z"]
output ["ABC","1",["x","y","z"]]
In this particular case you could do this:
mylist = ["ABC","1","x","y","z"]
offset = 2
newlist = mylist[:offset] + [mylist[offset:]]
print(newlist)
Output:
['ABC', '1', ['x', 'y', 'z']]
Try:
mylist = ["ABC","1","x","y","z"]
def nest(mylist, n):
"""Nests list from nth element"""
nest = [x for x in mylist[n:]]
mylist = mylist[:n]
mylist.append(nest)
return mylist
nest(mylist, 2)
I have a following problem. I would like to form a list a conditionally.
Lets say I have a variable add_string and if it's True then
a = ["a","b","Added String","c"]
Else
a = ["a","b","c"]
what's the best way to do that? I can do that in the following manner
a = ["a","b","c"]
if add_string:
a.insert(2,"Added String")
But that's not ideal since list a might change in future and I will have to change the index in the insert function. Also I have a condition — this added string should always follow after "b". Another solution is to search for "b" in the list and then insert after that, but that adds complexity and it's ugly.
Ideally I thought it should be something like
a = ["a","b",if add_string then "Added String","c"]
a = ["a","b"] + (["Added String"] if add_string else []) + ["c"]
If you know all the values when you create a, you could do something like this:
add_string = True
a = ['a', 'b'] + (['Added String'] if add_string else []) + ['c']
Output:
['a', 'b', 'Added String', 'c']
If you don't know the values in a, you could use index to find the location of 'b' in a, and insert the string after that:
a = ["a","b","c"]
add_string = True
if add_string:
a.insert(a.index("b")+1,"Added String")
print(a)
Output:
['a', 'b', 'Added String', 'c']
You could set unwanted values to a known value (such as None) and then remove them using list comprehension:
add_string = False # Could be True
unfiltered_list = ["a","b","Added String" if add_string else None,"c"]
a = [x for x in unfiltered_list if x is not None]
print(a)
I want to write a code that will replace certain characters in a list in an efficient way using a dictionary.
If I have:
key = {'a':'z','b':'y','c':'x'}
List = ['a','b','c']
How can I get the output
zyx
edit to clarify. The output I want is really
randomvariableorsomething = ['z', 'y', 'x']
My apologies.
Will [key[x] for x in List] work if I don't have a key for it in the dict?
Use get and join:
>>> ''.join(key.get(e,'') for e in List)
'zyx'
If by 'replace' you mean to change the list to the values of the dict in the order of the elements of the original list, you can do:
>>> List[:]=[key.get(e,'') for e in List]
>>> List
['z', 'y', 'x']
key = {'a':'z','b':'y','c':'x'}
List = ['a','b','c']
print([key.get(x,"No_key") for x in List])
#### Output ####
['z', 'y', 'x']
If your interest is only to print them as string,then:
print(*[key.get(x,"No_key") for x in List],sep="")
#### Output ####
zxy
Just in case you need the solution without join.
ss = ''
def fun_str(x):
global ss
ss = ss + x
return(ss)
print([fun_str(x) for x in List][-1])
#### Output ####
zxy
Both keys and List are words in python that can collide with existing objects or methods (dict.keys() and List objects), so I replaced them with k and lst respectively for best practice:
[k[x] for x in lst]
Assuming a python array "myarray" contains:
mylist = [u'a',u'b',u'c']
I would like a string that contains all of the elements in the array, while preserving the double quotes like this (notice how there are no brackets, but parenthesis instead):
result = "('a','b','c')"
I tried using ",".join(mylist), but it gives me the result of "a,b,c" and eliminated the single quotes.
You were quite close, this is how I would've done it:
result = "('%s')" % "','".join(mylist)
What about this:
>>> mylist = [u'a',u'b',u'c']
>>> str(tuple(map(str, mylist)))
"('a', 'b', 'c')"
Try this:
result = "({})".format(",".join(["'{}'".format(char) for char in mylist]))
>>> l = [u'a', u'b', u'c']
>>> str(tuple([str(e) for e in l]))
"('a', 'b', 'c')"
Calling str on each element e of the list l will turn the Unicode string into a raw string. Next, calling tuple on the result of the list comprehension will replace the square brackets with parentheses. Finally, calling str on the result of that should return the list of elements with the single quotes enclosed in parentheses.
What about repr()?
>>> repr(tuple(mylist))
"(u'a', u'b', u'c')"
More info on repr()
Here is another variation:
mylist = [u'a',u'b',u'c']
result = "\"{0}\"".format(tuple(mylist))
print(result)
Output:
"('a', 'b', 'c')"
What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, ['a', 'b', 'c'] to 'a,b,c'? (The cases ['s'] and [] should be mapped to 's' and '', respectively.)
I usually end up using something like ''.join(map(lambda x: x+',',l))[:-1], but also feeling somewhat unsatisfied.
my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
'a,b,c,d'
This won't work if the list contains integers
And if the list contains non-string types (such as integers, floats, bools, None) then do:
my_string = ','.join(map(str, my_list))
Why the map/lambda magic? Doesn't this work?
>>> foo = ['a', 'b', 'c']
>>> print(','.join(foo))
a,b,c
>>> print(','.join([]))
>>> print(','.join(['a']))
a
In case if there are numbers in the list, you could use list comprehension:
>>> ','.join([str(x) for x in foo])
or a generator expression:
>>> ','.join(str(x) for x in foo)
",".join(l) will not work for all cases. I'd suggest using the csv module with StringIO
import StringIO
import csv
l = ['list','of','["""crazy"quotes"and\'',123,'other things']
line = StringIO.StringIO()
writer = csv.writer(line)
writer.writerow(l)
csvcontent = line.getvalue()
# 'list,of,"[""""""crazy""quotes""and\'",123,other things\r\n'
Here is a alternative solution in Python 3.0 which allows non-string list items:
>>> alist = ['a', 1, (2, 'b')]
a standard way
>>> ", ".join(map(str, alist))
"a, 1, (2, 'b')"
the alternative solution
>>> import io
>>> s = io.StringIO()
>>> print(*alist, file=s, sep=', ', end='')
>>> s.getvalue()
"a, 1, (2, 'b')"
NOTE: The space after comma is intentional.
#Peter Hoffmann
Using generator expressions has the benefit of also producing an iterator but saves importing itertools. Furthermore, list comprehensions are generally preferred to map, thus, I'd expect generator expressions to be preferred to imap.
>>> l = [1, "foo", 4 ,"bar"]
>>> ",".join(str(bit) for bit in l)
'1,foo,4,bar'
Don't you just want:
",".join(l)
Obviously it gets more complicated if you need to quote/escape commas etc in the values. In that case I would suggest looking at the csv module in the standard library:
https://docs.python.org/library/csv.html
>>> my_list = ['A', '', '', 'D', 'E',]
>>> ",".join([str(i) for i in my_list if i])
'A,D,E'
my_list may contain any type of variables. This avoid the result 'A,,,D,E'.
l=['a', 1, 'b', 2]
print str(l)[1:-1]
Output: "'a', 1, 'b', 2"
#jmanning2k using a list comprehension has the downside of creating a new temporary list. The better solution would be using itertools.imap which returns an iterator
from itertools import imap
l = [1, "foo", 4 ,"bar"]
",".join(imap(str, l))
Here is an example with list
>>> myList = [['Apple'],['Orange']]
>>> myList = ','.join(map(str, [i[0] for i in myList]))
>>> print "Output:", myList
Output: Apple,Orange
More Accurate:-
>>> myList = [['Apple'],['Orange']]
>>> myList = ','.join(map(str, [type(i) == list and i[0] for i in myList]))
>>> print "Output:", myList
Output: Apple,Orange
Example 2:-
myList = ['Apple','Orange']
myList = ','.join(map(str, myList))
print "Output:", myList
Output: Apple,Orange
If you want to do the shortcut way :) :
','.join([str(word) for word in wordList])
But if you want to show off with logic :) :
wordList = ['USD', 'EUR', 'JPY', 'NZD', 'CHF', 'CAD']
stringText = ''
for word in wordList:
stringText += word + ','
stringText = stringText[:-2] # get rid of last comma
print(stringText)
Unless I'm missing something, ','.join(foo) should do what you're asking for.
>>> ','.join([''])
''
>>> ','.join(['s'])
's'
>>> ','.join(['a','b','c'])
'a,b,c'
(edit: and as jmanning2k points out,
','.join([str(x) for x in foo])
is safer and quite Pythonic, though the resulting string will be difficult to parse if the elements can contain commas -- at that point, you need the full power of the csv module, as Douglas points out in his answer.)
I would say the csv library is the only sensible option here, as it was built to cope with all csv use cases such as commas in a string, etc.
To output a list l to a .csv file:
import csv
with open('some.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(l) # this will output l as a single row.
It is also possible to use writer.writerows(iterable) to output multiple rows to csv.
This example is compatible with Python 3, as the other answer here used StringIO which is Python 2.
mmm also need for SQL is :
l = ["foo" , "baar" , 6]
where_clause = "..... IN ("+(','.join([ f"'{x}'" for x in l]))+")"
>> "..... IN ('foo','baar','6')"
enjoit
My two cents. I like simpler an one-line code in python:
>>> from itertools import imap, ifilter
>>> l = ['a', '', 'b', 1, None]
>>> ','.join(imap(str, ifilter(lambda x: x, l)))
a,b,1
>>> m = ['a', '', None]
>>> ','.join(imap(str, ifilter(lambda x: x, m)))
'a'
It's pythonic, works for strings, numbers, None and empty string. It's short and satisfies the requirements. If the list is not going to contain numbers, we can use this simpler variation:
>>> ','.join(ifilter(lambda x: x, l))
Also this solution doesn't create a new list, but uses an iterator, like #Peter Hoffmann pointed (thanks).