lIndexError:列表分配索引超出范围

时间:2018-08-21 20:04:49

标签: python python-3.x

此代码有什么问题。我正在尝试获得这样的输入- 4 5 || 3 6 并在S中存储4、3,在E中存储5、6

N=int(input())
S=[]
E=[]
for i in range(0,N):
    (S[i], E[i])=map(int, input().split(' '))

3 个答案:

答案 0 :(得分:0)

您不能在python中增加这样的列表。如果要添加到列表,则必须使用以下方法:

static void CheckIn(Uri urlCollection, string comment)
{
    Workspace workspace = GetWorkSpace(urlCollection, "MyWorkspace");
    WorkItem workItem = new TfsTeamProjectCollection(urlCollection).GetService<WorkItemStore>().GetWorkItem(12345);

    workspace.CheckIn(
        workspace.GetPendingChanges(), 
        "Autor", 
        comment, 
        new CheckinNote(new[] { new CheckinNoteFieldValue("Code Reviewer", "myself") }),
        new [] { new WorkItemCheckinInfo(workItem,WorkItemCheckinAction.Associate) },
        new PolicyOverrideInfo("override", new PolicyFailure[] {
            //My problem lies here, I don't know how to get all PolicyFailures
        }));
}

答案 1 :(得分:0)

在python中,当您拥有一个列表变量时,它具有特定的长度,如果尝试访问一个大于或等于该长度的数字的成员,它将抛出索引错误。现在要避免这种情况,您可以使用[]概念在一个通道中实例化数组,如下所示:(在此代码中,inputsSp变量是将输入拆分为相应成员的示例:例如,inputsSp [i] = ['4','5 ','||','3','6'])

S = [[int(inp[i][0]), int(inp[3])] for inp in inputsSp]
E = [[int(inp[i][1]), int(inp[4])] for inp in inputsSp] 

答案 2 :(得分:0)

您也可以通过以下方式进行操作:

namespace Google\Cloud\Samples\Auth;

// Imports the Google Cloud Storage client library.
use Google\Cloud\Storage\StorageClient;

function auth_cloud_explicit($projectId, $serviceAccountPath)
{
    # Explicitly use service account credentials by specifying the private key
    # file.
    $config = [
        'keyFilePath' => $serviceAccountPath,
        'projectId' => $projectId,
    ];
    $storage = new StorageClient($config);

    # Make an authenticated API request (listing storage buckets)
    foreach ($storage->buckets() as $bucket) {
        printf('Bucket: %s' . PHP_EOL, $bucket->name());
    }
}

或长版:

S, E = zip(*[map(int, input().split()) for _ in range(int(input()))])

通过输入所有输入,然后zip输入结果,然后根据需要对它们进行排序,可以正常工作。在repl.it上看到它:

num_of_pairs = int(input())
full_input = []
for _ in range(num_of_pairs):
    full_input.append(map(int, input().split()))  # add each pair to the full input
S, E = zip(*full_input)  # the * is important as this unpacks the list for zip