我希望我的Python函数分割一个句子(输入)并将每个单词存储在一个列表中.我当前的代码拆分了句子,但没有将单词存储为列表.我怎么做?
def split_line(text):
# split the text
words = text.split()
# for each word in the line:
for word in words:
# print the word
print(words)
Run Code Online (Sandbox Code Playgroud) 有没有更简单的方法将列表中的字符串项连接成一个字符串?
我可以使用该str.join()功能加入列表中的项目吗?
例如,这是输入['this','is','a','sentence'],这是所需的输出this-is-a-sentence
sentence = ['this','is','a','sentence']
sent_str = ""
for i in sentence:
sent_str += str(i) + "-"
sent_str = sent_str[:-1]
print sent_str
Run Code Online (Sandbox Code Playgroud) 如果我有一个字符列表:
a = ['a','b','c','d']
Run Code Online (Sandbox Code Playgroud)
如何将其转换为单个字符串?
a = 'abcd'
Run Code Online (Sandbox Code Playgroud) filter,map并且reduce在Python 2中完美地工作.这是一个例子:
>>> def f(x):
return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
>>> def cube(x):
return x*x*x
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> def add(x,y):
return x+y
>>> reduce(add, range(1, 11))
55
Run Code Online (Sandbox Code Playgroud)
但是在Python 3中,我收到以下输出:
>>> filter(f, range(2, 25))
<filter object at 0x0000000002C14908>
>>> map(cube, range(1, 11))
<map object at 0x0000000002C82B70> …Run Code Online (Sandbox Code Playgroud) python中有一个函数可以将单词拆分成单个字母列表吗?例如:
s="Word to Split"
Run Code Online (Sandbox Code Playgroud)
要得到
wordlist=['W','o','r','d','','t','o' ....]
Run Code Online (Sandbox Code Playgroud) 所以我想要做的就是从.txt文件中取出一行txt,然后将字符分配给一个列表,然后创建列表中所有单独字符的列表.
所以列表清单.
目前,我已经尝试过:
fO = open(filename, 'rU')
fL = fO.readlines()
Run Code Online (Sandbox Code Playgroud)
这就是我的最爱.我不太清楚如何提取单个字符并将它们分配给新列表.
我想做的事情如下:
fL = 'FHFF HHXH XXXX HFHX'
Run Code Online (Sandbox Code Playgroud)
^^^所以我是从.txt文件得到的行.
然后把它变成这个:
['F', 'H', 'F', 'F', 'H', ...]
Run Code Online (Sandbox Code Playgroud)
^^^和那是新的列表,每个单独的字符都在它自己的上面.
是否可以将字符串转换为列表,如下所示:
"5+6"
Run Code Online (Sandbox Code Playgroud)
成
["5", "+", "6"]
Run Code Online (Sandbox Code Playgroud) 我有以下代码:
stru = "??????????"
strlist = stru.decode("utf-8").split()
print strlist[0]
Run Code Online (Sandbox Code Playgroud)
我的输出是:
??????????
Run Code Online (Sandbox Code Playgroud)
但是当我使用时:
print strlist[1]
Run Code Online (Sandbox Code Playgroud)
我得到以下内容traceback:
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)
我的问题 是,我怎么能split我的string?当然,请记住我string从a 获得了function,认为它是一个variable?
我想知道如何获取用户输入并列出其中的每个字符.
magicInput = input('Type here: ')
Run Code Online (Sandbox Code Playgroud)
并且说你输入了"python rocks"我想让它成为这样的列表
magicList = [p,y,t,h,o,n, ,r,o,c,k,s]
Run Code Online (Sandbox Code Playgroud)
但如果我这样做:
magicInput = input('Type here: ')
magicList = [magicInput]
Run Code Online (Sandbox Code Playgroud)
magicList就是
['python rocks']
Run Code Online (Sandbox Code Playgroud)