>>> field_types = [str, int, float] >>> fields = [ty(val) for ty,val in zip(field_types,raw_fields)] >>> fields ['ACME', 100, 123.45] >>>
In this second example, if you want to convert data from a different file with different columns, you just make changes to field_types. All of the other code works without modification.
|This tip is written by David Beazley, author of the Python Essential Reference, now available in a new Fourth Edition. It is published by Addison-Wesley Professional, as part of its Developer's Library (informit.com/devlibrary), Copyright 2009 by Pearson Education, Inc. ISBN 0672329786. To read a sample chapter, on Types and Objects, please visit the publisher site: http://www.informit.com/title/0672329786 or, Safari Books Online subscribers can access the entire book here: http://safari.informit.com/9780768687040|