我在 Mac OSX Lion 上使用 Python 2.7
。我将 IPython
与 Pandas 0.11.0
、Numpy
和 Statsmodels
包一起使用。
我正在编写一个函数,允许用户对文件进行逻辑回归,指定在构建模型时使用哪些变量,哪些变量应该转换为虚拟变量以及哪个变量应该是自变量。
例如,当我执行以下操作时:
cols_to_keep = []
print (df.columns)
i = eval(raw_input('How many of these variables would you like to use in logistic regression?: '))
while i != 0:
i = i - 1
print (df.columns)
addTo = raw_input('Enter a variable for this list that you would like to keep and use in logistic regression.: ')
cols_to_keep.append(addTo)
我最终遇到了问题。具体来说,当我要求用户从列表中指定因变量,然后需要将该变量从训练变量列表中取出时:
print (df.columns)
dependent = raw_input('Which of these columns would you like to be the dependent variable?: ')
training.remove(dependent)
我发现,插入打印语句后,添加到训练变量列表中的变量如下所示:
('these are the traing variables: ', ['access', u'age_age6574', u'age_age75plus', u'sex_male', u'stage_late', u'death_death'])
似乎在每个用户指定的变量之前放置了一个u
。
我的问题是:为什么会这样以及如何修复/解决此问题,以便当用户指定因变量时,它实际上会从列表中删除。这种情况也会发生在用户指定变量并将其添加到列表中的所有其他情况下,如果我需要用户观察列表,则会造成困惑。
最佳答案
这些只是 unicode 字符串,而不是字节字符串。没有什么问题,字符串的内容不受影响。 u'text'
只是为了让您在查看 repr 时能够区分 Python 2 中的字节字符串和 unicode 字符串。如果打印该字符串,您将看不到任何差异。在 Python 3 中情况正好相反,其中 "text"
表示 unicode 字符串,而 b"bytes"
表示字节字符串。
如果你真的想将它们强制转换为字节串(不太可能),你可以这样做:
def ensure_str(s):
if isinstance(s, unicode):
s = s.encode('utf-8')
return s
s = ensure_str(raw_input("prompt >"))
关于Python 2.7 - IPython 'raw_input' 并附加到列表 - 在每个项目之前添加 'u',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17012908/