.index()生成AttributeError:'dict_values'对象没有属性'index'

时间:2018-03-01 14:10:19

标签: python

我正在尝试将此Python2代码重写为Python3接受的语法。 .index()方法会生成以下错误:

AttributeError:'dict_values'对象没有属性'index'

这是因为.index()在Python3中没有有效的语法。我已经读过应该使用列表解决问题,但我无法弄清楚如何做到这一点。任何人都知道如何解决这个问题?

words1 = [self._word_to_id.keys()[self._word_to_id.values().index(data_x[index])] for index in range(len(puncts) - 1)]
indices = [i for i, w in enumerate(words1) if w in PUNCTUATIONS]
for i in indices:
    words1[i], words1[i-1] = words1[i-1], words1[i] 
words2 = [self._word_to_id.keys([self._word_to_id.values().index(data_x[index])] for index in range(len(puncts) - 1, len(data_x))]
all_words = words1 + [puncts[-1]] + words2  
content = ' '.join(all_words)  
min_step = len(puncts)

2 个答案:

答案 0 :(得分:2)

您正在呼叫self._word_to_id.values(),而该dict_values会返回课程list,而不是dict_valueslist不会从index继承,也不会因此而导致list方法。

您需要将字典值转换为index才能使用list(self._word_to_id.values()).index(data_x[index]) 功能。试试这个:

private readonly ISession session;
private readonly ILogger logger;

public Startup(IConfiguration configuration)
{
  Configuration = configuration;

    var baseDirectory = Directory.GetDirectoryRoot(AppDomain.CurrentDomain.BaseDirectory);

    Log.Logger = new LoggerConfiguration()
                    .WriteTo
                    .Logger(lc => lc.Filter
                                    .ByIncludingOnly(e => e.Level == LogEventLevel.Information || e.Level == LogEventLevel.Debug)
                                    .WriteTo.RollingFile(Path.Combine(baseDirectory, "/Logs/info.log")))
                    .WriteTo
                    .Logger(lc => lc.Filter
                                    .ByIncludingOnly(e => e.Level == LogEventLevel.Error)
                                    .WriteTo.RollingFile(Path.Combine(baseDirectory, "/Logs/error.log")))

}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
  }

   loggerFactory.AddSerilog();
   ...//To shorten this example in Stackoverflow, I've excluded the standard code. But in reality they are of course there
}

答案 1 :(得分:1)

words1 = [list(self._word_to_id.keys())[list(self._word_to_id.values()).index(data_x[index])] for index in range(len(puncts) - 1)]