问题描述
我正在尝试学习Python列表。在这段代码中,我试图添加一个字符串 s
,只要字符串相同,它就会从表单行添加到表格行。当字符串不同时;新字符串被写入下一列。
I am trying to learn Python lists. In this code I am trying to add a string s
coming from a form to table row as long as the string is the same. When the string is different; the new string is written to the next column.
我可以将第0列
中的字符串写入第1列
但我在第1列
上正确添加相同的字符串时遇到了问题。
I could write the string from column 0
to column 1
but I had problems adding the same string on column 1
correctly.
它的方式;该脚本仅适用于将不同的字符串放到下一列。
The way it is; the script works only up to placing the different string to the next column.
我意识到这不是正确的做法。
I realize that this is not the right way of doing this.
我将不胜感激任何帮助。谢谢。我也包含了模板。
I would appreciate any help. Thank you. I include the template too.
EDIT2
@JerseyMike:谢谢你的支持回答。我还不知道 AddString(str)
是如何工作的,但是在IDLE中尝试它我注意到它不是添加新字符串而是用新字符串替换它。正如我所说,我还没有研究它是如何工作的;但这是结果(我将 str
更改为 str1
):
@JerseyMike: Thanks for your answer. I don't yet understand how AddString(str)
works but trying it in IDLE I noticed that instead of adding the new string it replaces it with the new string. As I said, I have not yet studied how it works; but here is the result (I changed str
to str1
):
>>> def AddString(str1):
try:
idx = map(lambda (s, v): ('N', 'Y')[s == str1], L).index('Y')
except:
L.append((str1, 1))
else: L[idx] = (str1, L[idx][1] + 1)
>>> L = []
>>> str1 = 'hello'
>>> AddString(str1)
>>> L
[('hello', 1)]
>>> AddString(str1)
>>> L
[('hello', 2)]
>>>
编辑
@JerseyMike:
@JerseyMike:
谢谢,对不起,我意识到问题不明确。在这个应用程序;用户输入相同的句子;喜欢练习外语。所以输入将是
Thanks, I am sorry, I realized the question was not clear. In this app; the user types in the same sentence; like practicing foreign language. So the input will be
Hello world
Hello world
Hello world
如果用户键入下一个Hello universe,将转到下一列:
and if the user types in next "Hello universe" that will go to the next column:
Hello world Hello Universe
Hello world
Hello world
如果用户不断输入Hello Universe,他们应该在同一列下面
and if the user keeps typing "Hello Universe" they should go under the same column
Hello world Hello Universe
Hello world Hello Universe
Hello world Hello Universe
Hello Universe
Hello Universe
包含此内容的列表L如下所示:
The list L containing this looks like this:
L = [
['Hello world', 'Hello Universe'],
['Hello world', 'Hello Universe'],
['Hello world', 'Hello Universe'],
['', 'Hello Universe'],
['', 'Hello Universe']
]
最初列表为空,我用<$ c $添加字符串 s
c> L.append(s)。
Initially the list is empty and I add the string s
with L.append(s)
.
L = [
['Hello world'],
['Hello world'],
['Hello world'],
]
如果最后一个字符串 s
与新输入不匹配,我用 L [0]创建新列.insert(1,s)
。
If the last string s
does not match the new input I create the new column with L[0].insert(1,s)
.
L = [
['Hello world', 'Hello Universe'],
['Hello world'],
['Hello world'],
]
现在我需要写下'Hello Universe'
这对我来说很困难原因。但是现在我认为在检查它是否与前一个字符串相同之前,最好将新字符串 s
附加到列表中。为了简化列表,假设 L
是这样的:
Now I need to write under 'Hello Universe'
This turned out to be difficult for me to figure out for several reasons. But now I think it may be better to append the new string s
to the list before checking if it is same as the previous string. To simplify the list, assume L
is like this:
L = [['A'], ['A'], ['A'], ['B']]
现在 ['B']
需要插入 L [0]
。为此,我搜索左侧的列表,找到包含1个元素的最后一个子列表(或类似的东西)。我还没有研究如何搜索列表。再次感谢您的帮助。
Now ['B']
needs to be inserted into L[0]
. To do this I search the list to the left to find the last sub-list with 1 element (or something like this). I have not looked into how to search lists yet. Thanks again for the help.
ENDEDİT
class Test(webapp.RequestHandler):
myList = []
def get(self):
# del self.myList[:]
s = [self.request.get('sentence')]
r = len(self.myList)
if r == 0:
self.myList.append(s)
htmlcode1 = HTML.table(self.myList)
lastItem = s
else:
if len(self.myList[0]) == 1:
lastItem = self.myList[r-1]
if s == lastItem:
self.myList.append(s)
htmlcode1 = HTML.table(self.myList)
else:
s = self.request.get('sentence')
self.myList[0].insert(1,s)
htmlcode1 = HTML.table(self.myList)
if len(self.myList[0]) == 2:
self.myList[1].insert(1,s)
htmlcode1 = HTML.table(self.myList)
elif len(self.myList[1]) == 2:
self.myList[2].insert(1,s)
htmlcode1 = HTML.table(self.myList)
template_values = {'htmlcode1': htmlcode1,
's': s,
'r': r,
'myList': self.myList,
# 'myListLen': myListLen,
'lastItem': lastItem,
}
path = os.path.join(os.path.dirname(__file__), 'test.mako')
templ = Template(filename=path)
self.response.out.write(templ.render(**template_values))
模板
<html>
<head>
</head>
<body>
<p>| <a href="/delete">CLEAR</a> |</p>
<form action="/test" method="get">
<input name="sentence" type="text" size="30"><br />
<input type="submit" value="Enter">
</form>
<p>${htmlcode1}</p>
<p>s: ${s}</p>
<p>r: ${r}</p>
<p>myList: ${myList}</p>
<p>lastItem: ${lastItem}</p>
</html>
</body>
推荐答案
如果字符串的顺序很重要,那么字典将是一个问题。你使用列表是正确的道路,但我认为你需要的不仅仅是这些。老实说,我不清楚你的输出对于不同的数据集会是什么样子。如果我正确地读了你的问题,是否真的如此?
If the order of the strings is important, a dictionary will be a problem. You are on the right path using lists, but I think you need more than just that. Honestly, I'm not clear on what your output will look like for different data sets. If I read your question correctly, is the following true?
输入:
Sentence 1
Sentence 3
Sentence 1
Sentence 1
Sentence 2
Sentence 2
最后一行后的输出:
Sentence 1 | Sentence 3 | Sentence 2
Sentence 1 | | Sentence 2
Sentence 1 | |
如果没有,请通过示例重新说明您的预期输出。
If not, please rephrase your expected output with an example.
好的,所以看起来我对你的问题的看法是正确的。这是一个好的开始。 ;)
Ok, so it looks like my take on your problem was correct. That's a good start. ;)
我认为我们需要从不同的角度来看待这个问题。目前,您正在将此视为所有数据的大列表,也许这太过分了。我在这里看到的是一个元组列表,其中每个元组代表一个列(字符串,计数)。元组将是该列中应该包含的字符串以及它们中应该有多少字符串。所以你的例子最终看起来像:
I think we need to look at this from a different perspective. Currently, you are looking at this as a big list of all the data and maybe that's too much. What I see here is a list of tuples, where each tuple represents a column (string, count). The tuple will be what string should be in this column and how many of them should be there. So your example would end up looking like:
L = [(Hello World,3),(Hello Universe,5) ]
我知道如何处理这些数据并不明显,但我认为这是在内部表示它的正确方法。我将给你一些示例代码来对这种数据类型进行一些基本的操作(其他人可能有更有效的方法来做同样的事情)。
I know this isn't obvious as to how to deal with this data, but I think it's the right way to represent it internally. I'll give you some sample code to do some basic manipulations of this data type (others may have more efficient ways of doing the same thing).
添加一个新的字符串:
def AddString(str):
try:
idx = map(lambda (s, v): ('N', 'Y')[s == str], L).index('Y')
except:
L.append( (str, 1) )
else:
L[idx] = (str, L[idx][1] + 1)
打印HTML表格内部:
Print the inside of an HTML table:
def PrintChart():
try:
max = reduce(lambda x, y: [x, y][x[1] < y[1]], L)[1]
except:
print "<td></td>"
else:
for i in range(max):
print "<tr>"
for (s, c) in L:
if i+1 <= c:
print " <td" + s + "</td>"
else:
print " <td></td>"
print "</tr>"
无论如何,这就是我的方式。
So anyway, that is the way I'd do it.
这篇关于Python列表的条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!