How to change/modify strings different in a list - python-2.7

I don't know if this question has been asked before, but it seems that I can't find the function that I am looking for. I want to add two different string to different strings in a list. Something like this:
old_list: ['spider','cat','iron','super','bat']
old_list: ['spiderman','catwoman','ironman','superwoman','batman']
So I want some kind of function that changes the strings by adding 'man' or 'woman' without making a new list. I think/know it can be done with some kind of for-loop but can't seem to find a easy way of doing it. And I am sorry if this question has been asked before, but I can't really find an answer to this specific function.

Slice-assign back into the list.
>>> ['{}{}'.format(pref, suff) for (pref, suff) in zip(old_list, itertools.cycle(('man', 'woman')))]
['spiderman', 'catwoman', 'ironman', 'superwoman', 'batman']
>>> id(old_list)
43518144
>>> old_list[:] = ['{}{}'.format(pref, suff) for (pref, suff) in zip(old_list, itertools.cycle(('man', 'woman')))]
>>> id(old_list)
43518144
>>> old_list
['spiderman', 'catwoman', 'ironman', 'superwoman', 'batman']

Just for the sake of a simpler answer, I will post this one:
for i in range(len(old_list)):
old_list[i] += suffixes[i%len(suffixes)]
Note you can have any number of suffixes.

Related

Trying to import dictionary to work with from a url; 'unicode' object not callable

I'm new to coding and have searched as best I can to find out how to solve this before asking.
I'm trying to pull information from poloniex.com REST api, which is in JSon format I believe. I can import the data, and work with it a little bit, but when I try to call and use the elements in the contained dictionaries, I get "'unicode' object not callable". How can I use this information? The end goal with this data is to pull the "BTC: "(volume)" for each coin pair and test if it is <100, and if not, append it to a new list.
The data is presented like this or you can see yourself at https://poloniex.com/public?command=return24hVolume:
{"BTC_LTC":{"BTC":"2.23248854","LTC":"87.10381314"},"BTC_NXT":{"BTC":"0.981616","NXT":"14145"}, ... "totalBTC":"81.89657704","totalLTC":"78.52083806"}
And my code I've been trying to get to work with currently looks like this(I've tried to iterate the information I want a million different ways, so I dunno what example to give for that part, but this is how I am importing the data):
returnvolume = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=return24hVolume'))
coinvolume = json.loads(returnvolume.read())
coinvolume = dict(coinvolume)
No matter how I try to use the data I've pulled, I get an error stating:
"unicode' object not callable."
I'd really appreciate a little help, I'm concerned I may be approaching this the wrong way as I haven't been able to get anything to work, or maybe I'm just missing something rudimentary, I'm not sure.
Thank you very much for your time!
Thanks to another user, downshift, I have discovered the answer!
d = {}
for k, v in coinvolume.items():
try:
if float(v['BTC']) > 100:
d[k] = v
except KeyError:
d[k] = v
except TypeError:
if v > 100:
d[k] = k
This creates a new list, d, and adds every coin with a 'BTC' volume > 100 to this new list.
Thanks again downshift, and I hope this helps others as well!

Printing Values from a list without spaces in python 2.7

Suppose I have a list like
list1 = ['A','B','1','2']
When i print it out I want the output as
AB12
And not
A B 1 2
So far I have tried
(a)print list1,
(b)for i in list1:
print i,
(c)for i in list1:
print "%s", %i
But none seem to work.
Can anyone suggest an alternate method
Thank you.
From your comments on #jftuga answer, I guess that the input you provided is not the one you're testing with. You have mixed contents in your list.
My answer will fix it for you:
lst = ['A','B',1,2]
print("".join([str(x) for x in lst]))
or
print("".join(map(str,lst)))
I'm not just joining the items since not all of them are strings, but I'm converting them to strings first, all in a nice generator comprehension which causes no memory overhead.
Works for lists with only strings in them too of course (there's no overhead to convert to str if already a str, even if I believed otherwise on my first version of that answer: Should I avoid converting to a string if a value is already a string?)
Try this:
a = "".join(list1)
print(a)
This will give you: AB12
Also, since list is a built-in Python class, do not use it as a variable name.

Testing for an item in lists - Python 3

As part of a school project we are creating a trouble shooting program. I have come across a problem that I cannot solve:
begin=['physical','Physical','Software','software',]
answer=input()
if answer in begin[2:3]:
print("k")
software()
if answer in begin[0:1]:
print("hmm")
physical()
When I try to input software/Software no output is created. Can anybody see a hole in my code as it is?
In Python, slice end values are exclusive. You are slicing a smaller list than you think you are:
>>> begin=['physical','Physical','Software','software',]
>>> begin[2:3]
['Software']
>>> begin[0:1]
['physical']
Use begin[2:4] and begin[0:2] or even begin[2:] and begin[:2] to get all elements from the 3rd to the end, and from the start until the 2nd (inclusive):
>>> begin[2:]
['Software', 'software']
>>> begin[2:4]
['Software', 'software']
>>> begin[:2]
['physical', 'Physical']
>>> begin[0:2]
['physical', 'Physical']
Better yet, use str.lower() to limit the number of inputs you need to provide:
if answer.lower() == 'software':
With only one string to test, you can now put your functions in a dictionary; this gives you the option to list the various valid answers too:
options = {'software': software, 'physical': physical}
while True:
answer = input('Please enter one of the following options: {}\n'.format(
', '.join(options))
answer = answer.lower()
if answer in options:
options[answer]()
break
else:
print("Sorry, {} is not a valid option, try again".format(answer))
Your list slicing is wrong, Try the following script.
begin=['physical','Physical','Software','software',]
answer=input()
if answer in begin[2:4]:
print("k")
software()
if answer in begin[0:2]:
print("hmm")
physical()

filter output of subprocess.check_output

I'm trying to match values of a list to a regex pattern. If the particular value within the list matches, I'll append it to a different list of dicts. If the above mentioned value does not match, I want to remove the value from the list.
import subprocess
def list_installed():
rawlist = subprocess.check_output(['yum', 'list', 'installed']).splitlines()
#print rawlist
for each_item in rawlist:
if "[\w86]" or \
"noarch" in each_item:
print each_item #additional stuff here to append list of dicts
#i haven't done the appending part yet
#the list of dict's will be returned at end of this funct
else:
remove(each_item)
list_installed()
The end goal is to eventually be able to do something similar to:
nifty_module.tellme(installed_packages[3]['version'])
nifty_module.dosomething(installed_packages[6])
Note to gnu/linux users going wtf:
This will eventually grow into a larger sysadmin frontend.
Despite the lack of an actual question in your post, I'll make a couple of comments.
You have a problem here:
if "[\w86]" or "noarch" in each_item:
It's not interpreted the way you think of it and it always evaluates to True. You probably need
if "[\w86]" in each_item or "noarch" in each_item:
Also, I'm not sure what you are doing, but in case you expect that Python will do regex matching here: it won't. If you need that, look at re module.
remove(each_item)
I don't know how it's implemented, but it probably won't work if you expect it to remove the element from rawlist: remove won't be able to actually access the list defined inside list_installed. I'd advise to use rawlist.remove(each_item) instead, but not in this case, because you are iterating over rawlist. You need to re-think the procedure a little (create another list and append needed elements to it instead of removing, for example).

convert List[Tuple2[A,B]] to Tuple2[Seq[A],Seq[B]]

Stuck here, trying to convert a List of case class tuples to a tuple of sequences and multi-assign the result.
val items = repo.foo.list // gives me a List[(A,B)]
I can pull off multi-assignment like so:
val(a,b) = (items.map(_._1).toSeq, items.map(_._2).toSeq)
but it would be nicer to do in 1 step, along the lines of:
val(a,b) = repo.foo.list.map{case(a,b) => (a,b)}
I am not sure if I understood the question correctly. Maybe unzip works for what you want?
Here is a link with some examples: http://daily-scala.blogspot.de/2010/03/unzip.html
For a more general case you can look at product-collections. A CollSeqN is both a Seq[TupleN[A1..An]] and a TupleN[Seq[A1..An]]
In your example you could extract the Seqs like so:
items._1
items._2
...