加入特定的字符串索引python

时间:2016-04-23 21:33:03

标签: python python-3.x

在python中,我正在创建一个打印程序,它从一个文件(从命令行运行时输入)读取以下行:import java.util.*; /** * A map where {@link #keySet()} and {@link #entrySet()} return sets ordered * with ascending associated values with respect to the the comparator provided * at constuction. The order of two or more keys with identical values is not * defined. * <p> * Several contracts of the Map interface are not satisfied by this minimal * implementation. */ public class ValueSortedMap<K, V> extends HashMap<K, V> { protected Map<V, Collection<K>> valueToKeysMap; public ValueSortedMap() { this((Comparator<? super V>) null); } public ValueSortedMap(Comparator<? super V> valueComparator) { this.valueToKeysMap = new TreeMap<V, Collection<K>>(valueComparator); } public boolean containsValue(Object o) { return valueToKeysMap.containsKey(o); } public V put(K k, V v) { V oldV = null; if (containsKey(k)) { oldV = get(k); valueToKeysMap.get(oldV).remove(k); } super.put(k, v); if (!valueToKeysMap.containsKey(v)) { Collection<K> keys = new ArrayList<K>(); keys.add(k); valueToKeysMap.put(v, keys); } else { valueToKeysMap.get(v).add(k); } return oldV; } public void putAll(Map<? extends K, ? extends V> m) { for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) put(e.getKey(), e.getValue()); } public V remove(Object k) { V oldV = null; if (containsKey(k)) { oldV = get(k); super.remove(k); valueToKeysMap.get(oldV).remove(k); } return oldV; } public void clear() { super.clear(); valueToKeysMap.clear(); } public Set<K> keySet() { LinkedHashSet<K> ret = new LinkedHashSet<K>(size()); for (V v : valueToKeysMap.keySet()) { Collection<K> keys = valueToKeysMap.get(v); ret.addAll(keys); } return ret; } public Set<Map.Entry<K, V>> entrySet() { LinkedHashSet<Map.Entry<K, V>> ret = new LinkedHashSet<Map.Entry<K, V>>(size()); for (Collection<K> keys : valueToKeysMap.values()) { for (final K k : keys) { final V v = get(k); ret.add(new Map.Entry<K,V>() { public K getKey() { return k; } public V getValue() { return v; } public V setValue(V v) { throw new UnsupportedOperationException(); } }); } } return ret; } } 。 但是,当我使用line 'hello world'的空格拆分此字符串时,它会按预期返回数组file.readline().split(" ")。有没有办法可以将两个索引["line", "'hello", "world'\n"]"'hello"转换为一个索引"world'\n",而无需创建没有"'hello world'\n"的新数组?

1 个答案:

答案 0 :(得分:0)

使用file.readline().split(" ")[1:]

这将创建一个数组,其中包含file.readline().split(" ")给出的数组中除第一个项目之外的所有项目

然后你可以在该数组上循环for循环并使用

将所有内容连接到一个字符串
for i in file.readline().split(" ")[1:]:
    str += (file.readline().split(" ")[1:])[i] + " "