Not getting what I want using the format function - python

Ok. I have a CSV, and I'm trying to use the format function to rearrange the order in which the data of the columns prints.
In other words, how can I use the format function to print columns in the order e,d,c instead of the default c,d,e?
Here's what I have so far:
for row in books:
print [item.upper() for item in row]
print [format(item[])
What am I missing here?

Formatting strings
I am not sure what are you asking for, but this may suit your needs:
>>> my_items = ['c', 'd', 'e']
>>> print '{2} {1} {0}'.format(*my_items)
e d c
It uses formatting, which allows you to print items in any order you like. See documentation of format() for more.
Reversing lists
If you want just to reverse order of the array, just provide -1 for "step" part within brackets after list's name:
>>> my_items = ['c', 'd', 'e']
>>> my_items[::-1]
['e', 'd', 'c']
so your code may look like this:
for row in books:
print [item.upper() for item in row[::-1]]
which will print list of uppercase items in a row, but in reversed order.

If you want to change the order of the columns, you can do:
for row in books:
print list(reversed(row)) # Prints the reversed row, as a list
print ', '.join(reversed(row)) # Prints a single string of comma-separated values
print [row[index] for index in (2, 0, 1)] # General order change
print ', '.join(row[index] for index in (2, 0, 1)) # Same thing, but prints a string

Isolating the column order from the input data is a good use for DictWriter.
>>> data = [range(i, i+3) for i in range(5)]
>>> import csv, StringIO
>>> f = StringIO.StringIO()
Create the writer, with fields in the order you need.
>>> writer = csv.DictWriter(f, ('e', 'd', 'c'))
And create some way to make a dict that has those keys, from whatever your input is.
>>> def datamap(row):
... return dict(zip('cde', row))
...
Then it's just a matter of using the csv writer as normal. (writeheader() is just a convenience so we can see what the columns look like, it is by no means mandatory)
>>> writer.writeheader()
>>> for datum in data:
... writer.writerow(datamap(datum))
...
>>> print f.getvalue()
e,d,c
2,1,0
3,2,1
4,3,2
5,4,3
6,5,4
>>>

Related

Python: Using Tuples get filtered list

Input Format :
The first line of input is an integer that corresponds to the number of records, 'n'.
The next 'n' line corresponds to the records.
The last line of input consists of the date to be filtered.
Output format :
The first line of the output is a set of comma seperated strings containing the cargo name and date.
The next lines consists of the names of the cargos printed one next to the other seperated by new line.
Refer to sample input and output for formatting specifications and more details.
Sample Input 1:
5
Allegan,11-12-2013
Douglas,29-12-2016
Junkers,27-03-2017
Biruinta,10-04-2014
ABC,27-03-2017
27-03-2016
Expected Sample Output 1:
[('Allegan', '11-12-2013'), ('Douglas', '29-12-2016'), ('Junkers', '27-03-2017'), ('Biruinta', '10-04-2014'), ('ABC', '27-03-2017')]
Douglas
Junkers
ABC
Code that was written:
n=int(input())
list1=[]
i=0
for i in range(0,n):
string1=raw_input()
i+=1
string1=string1.split()
for item in string1:
list1.append(item)
dateformat=raw_input()
mutuple = tuple(list1)
I am unable to split input from my list and get desired output by comparing as per the question. Can you please help
You can pass the delimiters to the split function:
In [1]: "a,b,c,d,e,f".split(",")
Out[1]: ['a', 'b', 'c', 'd', 'e', 'f']
I also wouldn't do string1=string1.split(), because the return of split is
a list and the variable is called string. Sure it's not incorrect, but that
might confuse you later more than it helps.
Also
for item in string1:
list1.append(item)
...
mutuple = tuple(list1)
is redundant, you just can do mutuple = tuple(string1). But that's not
probably what you want.
long_list = []
ls = tuple("a,b".split(","))
long_list.append(ls)
ls = tuple("c,d".split(","))
long_list.append(ls)
print long_list
# prints [('a', 'b'), ('c', 'd')]

How to concatenate strings into parenthesis in Python

In Python I have this loop that e.g. prints some value:
for row in rows:
toWrite = row[0]+","
toWrite += row[1]
toWrite += "\n"
Now this works just fine, and if I print "toWrite" it would print this:
print toWrite
#result:,
A,B
C,D
E,F
... etc
My question is, how would I concatenate these strings with parenthesis and separated with commas, so result of loop would be like this:
(A,B),(C,D),(E,F) <-- the last item in parenthesis, should not contain - end with comma
You'd group your items into pairs, then use string formatting and str.join():
','.join(['({},{})'.format(*pair) for pair in zip(*[iter(rows)] * 2)])
The zip(*[iter(rows)] * 2) expression produces elements from rows in pairs.
Each pair is formatted with '({},{})'.format(*pair); the two values in pair are slotted into each {} placeholder.
The (A,B) strings are joined together into one long string using ','.join(). Passing in a list comprehension is marginally faster than using a generator expression here as str.join() would otherwise convert it to a list anyway to be able to scan it twice (once for the output size calculation, once for building the output).
Demo:
>>> rows = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
>>> ','.join(['({},{})'.format(*pair) for pair in zip(*[iter(rows)] * 2)])
'(A,B),(C,D),(E,F),(G,H)'
Try this:
from itertools import islice, izip
','.join(('(%s, %s)' % (x, y) for x, y in izip(islice(rows, 0, None, 2), islice(rows, 1, None, 2))))
Generator and iterators are adopted here.
See itertools for a reference.

Convert a list to a string without 'join'

I'm trying to create my own function that converts a list of characters into a string. I'm not allowed to use 'join'. I need to use a loop to do this. I think I have the basis of it right, but I'm not really sure how to implement it into the function properly. I'm new to programming.
Here's the code I'm using:
def to_string(my_list):
# This line will eventually be removed - used for development purposes only.
print("In function to_string()")
# Display letters in a single line
for i in range(len(my_list)):
print(my_list[i], end='')
# Separate current letter from the next letter
if i<(len(my_list))-1:
print(", ", end='')
# Returns the result
return ('List is:', my_list)
That returns the result I want (if the list is ['a', 'b', 'c'] it returns a, b, c). But there's a 'test file' we're meant to use to run the function which contains this code:
print("\nto_string Test")
string = list_function.to_string(str_list1)
print(string)
print(list_function.to_string(empty))
And it gives this result:
to_string Test
In function to_string()
r, i, n, g, i, n, g('List is:', ['r', 'i', 'n', 'g', 'i', 'n', 'g'])
In function to_string()
('List is:', [])
Which seems to indicate that I messed up entirely, something to do with the 'print' function I think. Can anyone please tell me where I'm going wrong?
Your function prints your string to stdout, then returns the list itself unchanged.
Build a string and return that instead of printing:
def to_string(my_list):
result = ''
last = len(my_list) - 1
for pos, elem in enumerate(my_list):
result += str(elem)
if pos != last:
result += ', '
return result
This loops over all elements, keeping a position counter with the enumerate() function; this way it's easy to detect if we are adding the last element to the result.
You could also use reduce function:
aList=['w','o','r','d']
aString=reduce(lambda x,y:x+y,aList)
If you want to emulate the .join() method of strings than you may want to add a delimiter option to your function.
def to_string(my_list, delimiter):
string = str(my_list.pop(0))
while my_list:
string += delimiter + str(my_list.pop(0))
return string
.pop(n) will delete the nth element from the list and return it.
If you want to return the original list as well:
def to_string(my_list, delimiter):
string = ''
if my_list:
string = my_list[0]
for elem in my_list[1:]:
string += delimiter + str(elem)
return my_list, string
The syntax my_list[n] will get the nth element from the list. Note that the elements are numbered from 0, not from 1. The syntax my_list[n:] will return the elements of the list starting from n. Example:
>>> my_list = ['this', 'is', 'a', 'list']
>>> my_list[1:]
['is', 'a', 'list']
Loop over the list elements and add them to your string. (Just a simpler version of the proposed solutions)
def to_string(my_list):
result_string = ''
for element in my_list:
result_string += element
return result_string
To test:
a_list = ['r', 'i', 'n', 'g', 'i', 'n', 'g']
print to_string(a_list) # prints ringing
b_list = []
print to_string(b_list) # returns empty
Maybe a unique way of doing it.
#Python print() has a unique ability
List = ['a','b','c']
print(*List,sep="")
#### Output ####
abc
# In this method I'm trying to using python's print() ability
# and redirecting the print() from standard output to a temporary variable
# and then using it.
from io import StringIO # Python3
import sys
old_stdout = sys.stdout
result = StringIO() #store everything that is sent to the standard output
sys.stdout = result
print(*List, sep = "") #sends to variable result
#or do any fancy stuff here
sys.stdout = old_stdout # Redirect again the std output to screen
result_string = result.getvalue().strip() # strip() because it has \n at the end
print(result_string,type(result_string),len(result_string),sep="\n")
#this actually prints(), and also the result_string variable has that value
#### Output ####
abc
<class 'str'>
3
This will help you indetail. Store standard output on a variable in Python

How to "properly" print a list?

So I have a list:
['x', 3, 'b']
And I want the output to be:
[x, 3, b]
How can I do this in python?
If I do str(['x', 3, 'b']), I get one with quotes, but I don't want quotes.
In Python 2:
mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))
In Python 3 (where print is a builtin function and not a syntax feature anymore):
mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))
Both return:
[x, 3, b]
This is using the map() function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join(). Then, the % string formatting operator substitutes the string in instead of %s in "[%s]".
This is simple code, so if you are new you should understand it easily enough.
mylist = ["x", 3, "b"]
for items in mylist:
print(items)
It prints all of them without quotes, like you wanted.
Using only print:
>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b
If you are using Python3:
print('[',end='');print(*L, sep=', ', end='');print(']')
Instead of using map, I'd recommend using a generator expression with the capability of join to accept an iterator:
def get_nice_string(list_or_iterator):
return "[" + ", ".join( str(x) for x in list_or_iterator) + "]"
Here, join is a member function of the string class str. It takes one argument: a list (or iterator) of strings, then returns a new string with all of the elements concatenated by, in this case, ,.
You can delete all unwanted characters from a string using its translate() method with None for the table argument followed by a string containing the character(s) you want removed for its deletechars argument.
lst = ['x', 3, 'b']
print str(lst).translate(None, "'")
# [x, 3, b]
If you're using a version of Python before 2.6, you'll need to use the string module's translate() function instead because the ability to pass None as the table argument wasn't added until Python 2.6. Using it looks like this:
import string
print string.translate(str(lst), None, "'")
Using the string.translate() function will also work in 2.6+, so using it might be preferable.
Here's an interactive session showing some of the steps in #TokenMacGuy's one-liner. First he uses the map function to convert each item in the list to a string (actually, he's making a new list, not converting the items in the old list). Then he's using the string method join to combine those strings with ', ' between them. The rest is just string formatting, which is pretty straightforward. (Edit: this instance is straightforward; string formatting in general can be somewhat complex.)
Note that using join is a simple and efficient way to build up a string from several substrings, much more efficient than doing it by successively adding strings to strings, which involves a lot of copying behind the scenes.
>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'
Using .format for string formatting,
mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))
Output:
[x, 3, b]
Explanation:
map is used to map each element of the list to string type.
The elements are joined together into a string with , as separator.
We use [ and ] in the print statement to show the list braces.
Reference:
.format for string formatting PEP-3101
I was inspired by #AniMenon to write a pythonic more general solution.
mylist = ['x', 3, 'b']
print('[{}]'.format(', '.join(map('{}'.format, mylist))))
It only uses the format method. No trace of str, and it allows for the fine tuning of the elements format.
For example, if you have float numbers as elements of the list, you can adjust their format, by adding a conversion specifier, in this case :.2f
mylist = [1.8493849, -6.329323, 4000.21222111]
print("[{}]".format(', '.join(map('{:.2f}'.format, mylist))))
The output is quite decent:
[1.85, -6.33, 4000.21]

Using an index to get an item

I have a list in python ('A','B','C','D','E'), how do I get which item is under a particular index number?
Example:
Say it was given 0, it would return A.
Given 2, it would return C.
Given 4, it would return E.
What you show, ('A','B','C','D','E'), is not a list, it's a tuple (the round parentheses instead of square brackets show that). Nevertheless, whether it to index a list or a tuple (for getting one item at an index), in either case you append the index in square brackets.
So:
thetuple = ('A','B','C','D','E')
print thetuple[0]
prints A, and so forth.
Tuples (differently from lists) are immutable, so you couldn't assign to thetuple[0] etc (as you could assign to an indexing of a list). However you can definitely just access ("get") the item by indexing in either case.
values = ['A', 'B', 'C', 'D', 'E']
values[0] # returns 'A'
values[2] # returns 'C'
# etc.
You can use _ _getitem__(key) function.
>>> iterable = ('A', 'B', 'C', 'D', 'E')
>>> key = 4
>>> iterable.__getitem__(key)
'E'
Same as any other language, just pass index number of element that you want to retrieve.
#!/usr/bin/env python
x = [2,3,4,5,6,7]
print(x[5])
You can use pop():
x=[2,3,4,5,6,7]
print(x.pop(2))
output is 4

Categories