2015-10-15 76 views
0

我有一个嵌套字典,我正在使用它来拉取值。我使用字母作为键,其值依赖于字符串中的字母位置。Python - 基于字符串内字符位置的条件句

我试图对它进行编码,以便在字符串中找到字母时,它会为字符串中的位置提取准确的值。我有3个位置 - “首发”和“终结者”分别是第一个和最后四个字符。其他任何东西都是“中”。

我试过让字符在字符串中的位置作为一个整数,我可以很容易地输入到一个条件序列。

def Calc(letterstring, data_table): 
    Places= len(string) 
    Score = 0.0 

    for i in range(Places): 
     letter= string[i] 
     if [i] >= int(3) and [i] <= ((Places)-4): 
      position_in_string = "Starter" 
     elseif [i] >= ((Places)-4): 
      position_in_string = "Finisher" 
     else: 
      position_in_string = "Mid" 

     position = (position_in_string) 

     Score += data_table[letter][position] 

    return Score 

string = input("Insert your line here: ") # Something like ABCDEFGHIJKLMNOP 
total_score= (Calc((string), (data_table))) 
print (total_score) 

我期待输出一个整数。

但是,如果我尝试做这样,我结束了:

TypeError: unorderable types: list() >= int() 

任何建议或意见将受到欢迎!

+1

你能告诉一个例子输入您想要的输出是什么?从你的描述中不清楚你想要做什么。 – CoryKramer

+1

在您的循环中将'[i]'替换为'i'。 – luoluo

+0

'data_table'应该是什么,一个'dict'?如果是,那么'data_table'的例子会是什么样子? – Salo

回答

0

一些变化,我建议:

  1. Python有一个枚举内置,将采取一个序列(包括字符串)和序列
  2. 使用中的每个元素都返回索引和值letterstring一贯在你的函数中,一般来说,使用“字符串”作为变量名是皱眉
  3. 我假设data_table是字典的字典,这样的外部字典有keys = to'AZ'(注意.upper()以确保'a'被转换为'A'等。您应该也可以添加一些错误检查以防用户pu在ABC1 TS),和内部字典有3串设置(精简,装订和中间)

no idea why this is getting dorked up formatting

def Calc(letterstring, data_table): 
    Score = 0.0 
    ls = len(letterstring) 
    for i,letter in enumerate(letterstring): 
     if i < 4: 
      position_in_string = "Starter" 
     elif i >= (ls-4): 
      position_in_string = "Finisher" 
     else: 
      position_in_string = "Mid" 

     Score += data_table[letter][position_in_string] 

    return Score 

instring = input("Insert your line here: ") # Something like ABCDEFGHIJKLMNOP 
total_score= Calc(instring.upper(), data_table) 
print (total_score) 
+0

谢谢。罗洛和你自己的回答非常有帮助。 – 534